def __init__(self, stage, width, height, bombs): self._fieldAsset = FieldAsset() self._specAsset = SpecAsset() self._fields = self._fieldAsset.getAssets() self._special = self._specAsset.getAssets() self._fileController = FileController(stage) self._flags = bombs self._stage = stage self._czas = time.time() self._bombs = bombs self._width = width self._height = height self._count = 0 self._elements = width * height self._count = width * height self._bottomFrame = Frame(stage) self._state = 'game' self.createMenu() self.createButton(stage) self.createBombs() self.createMenuBar()
def createPOMFile(projectName, groupId, projectDir): ScriptMonitor.message("Creating the model file: pom.xml"); dict = {"{project.name}" : projectName, "{artifact.id}": projectName, "{group.id}": groupId, "{version}": "1.0", "{list-dependencies}" : FileGenerator.readDependencyFile(), "{application.entrypoint}" : groupId+".app.MainApplication"}; pomcontent = FileController.readFile("templates/pom.template"); str = pomcontent; for i, j in dict.items(): str = str.replace(i, j); FileController.writeToFile(str, projectDir+"/pom.xml");
class TweetsController(object): """description of class""" def __init__(self): self.lista = list() self.fileController = FileController() self.indexController = IndexController() def printTweets(self): for t in self.lista: print("======== ID: " + str(t.id) + " User: @" + t.user + " ========") print(t.message + ">>>") print("Data:" + str(t.datetime)) for tag in t.hashtags: print(tag + " " + str(len(tag))) print(len(t.hashtags)) def listTweets(self, tweets): for t in tweets: self.lista.append( Tweet(t.id, t.user.screen_name, t.text, self.getHashtags(t.text), t.created_at)) def saveTweets(self): for t in self.lista: self.fileController.saveTweet(t) #self.fileController.show() #self.indexController.show() @staticmethod def getHashtags(text): s_return = list() aux = "" for i in range(1, len(text)): if (text[i] != '#' and text[i] != ' ' and text[i] != '…'): aux = aux + text[i] if (text[i] == '#' or text[i] == '…'): s_return.append('#' + aux) aux = "" s_return.pop(0) return s_return
def readDependencyFile(): lines = FileController.readFileAndReturnLines("local/dependencies.txt"); dependencyString = ""; for e in lines [1:]: dependencyString += "<dependency>\n"+Utils.tabs(3); record = e.split(","); dependencyString += "<artifactId>"+record[0]+"</artifactId>\n"+Utils.tabs(3); dependencyString += "<groupId>"+record[1]+"</groupId>\n"+Utils.tabs(3); dependencyString += "<version>"+record[2].strip()+"</version>\n"+Utils.tabs(2); dependencyString += "</dependency>\n"+Utils.tabs(2); return dependencyString;
def init(): rest = None if (USE_REST): print('Start REST server') rest = RESTThread() rest.start() bin = None if (USE_BINLOG): bin = BinaryFileController(2) bin.start() acc = Accelerometer(0.250, bin) acc.start() log = None if (USE_TEXTLOG): log = FileController(20) log.start() dsp = Display(acc, log, rest) dsp.start() print('at sleep') time.sleep(60 * 30) acc.stopit() acc.join() print("Accelorometer stopped") dsp.stopit() dsp.join() print("Display stopped") if (USE_BINLOG): bin.stopit() bin.join() print("BinLogger stopped") if (USE_TEXTLOG): log.stopit() log.join() print("FileController stopped") if (USE_REST): rest.stopit() rest.join() print("REST server stopped") time.sleep(2) print("End")
def resumable_upload(insert_request, filename): response = None error = None retry = 0 while response is None: try: #print "Uploading file..." status, response = insert_request.next_chunk() if 'id' in response: #print "Video id '%s' was successfully uploaded." % response['id'] print response['id'] f = FileController() f.process_json() f.write_link(filename, response['id']) return response['id'] else: exit("The upload failed with an unexpected response: %s" % response) except HttpError, e: if e.resp.status in RETRIABLE_STATUS_CODES: error = "A retriable HTTP error %d occurred:\n%s" % ( e.resp.status, e.content) else: raise except RETRIABLE_EXCEPTIONS, e: error = "A retriable error occurred: %s" % e
def init(): rest = None if (USE_REST): print('Start REST server') rest = RESTThread() rest.start() bin = None if (USE_BINLOG): bin = BinaryFileController(2) bin.start() acc = Accelerometer(0.250, bin) acc.start() log = None if (USE_TEXTLOG): log = FileController(20) log.start() dsp = Display(acc, log, rest) dsp.start() print('at sleep') time.sleep(60*30) acc.stopit() acc.join() print("Accelorometer stopped") dsp.stopit() dsp.join() print("Display stopped") if (USE_BINLOG): bin.stopit() bin.join() print("BinLogger stopped") if (USE_TEXTLOG): log.stopit() log.join() print("FileController stopped") if (USE_REST): rest.stopit() rest.join() print("REST server stopped") time.sleep(2) print("End")
def queryloop(stemming, directory='lookup'): FC = FileController() FCs = FileController(stemming=True) # stemming = False looping = True while looping: user_input = input("Enter search query:\t").strip() if user_input[:2] == '->': user_input = user_input[2:].strip() if user_input == "exit": looping = False elif user_input == "clear": os.system('cls') elif user_input == 'stemming': print('stemming: ', stemming) elif user_input[:8] == 'stemming': new_state = user_input[8:].strip().lower() if new_state == 'false': stemming = False elif new_state == 'true': stemming = True else: print('unknown stemming state: must be true or false') print('stemming: ', stemming) else: print('unknown command') else: try: directory = 'stemming' if stemming else 'lookup' print(user_input) documents = QueryProcessing.process(user_input, directory=directory) except Exception as e: print('An error occured \n', e) documents = set() i = 1 for docID in documents: doc = FCs.get(docID) if stemming else FC.get(docID) doc = list( map(lambda x: x.encode('utf-8').decode('ascii', 'ignore'), doc)) print('%s:' % (i), doc[0], doc[1]) i += 1 print(len(documents), 'results found') print('---\n')
def test_loadScore(self): stage = Tk() fileController = FileController(stage) fileController.loadScore() self.assertEqual(fileController.rekordy[0][0], 'Rekordy poziom Łatwy')
class Game(object): def __init__(self, stage, width, height, bombs): self._fieldAsset = FieldAsset() self._specAsset = SpecAsset() self._fields = self._fieldAsset.getAssets() self._special = self._specAsset.getAssets() self._fileController = FileController(stage) self._flags = bombs self._stage = stage self._czas = time.time() self._bombs = bombs self._width = width self._height = height self._count = 0 self._elements = width * height self._count = width * height self._bottomFrame = Frame(stage) self._state = 'game' self.createMenu() self.createButton(stage) self.createBombs() self.createMenuBar() def createMenu(self): self._bottomFrame.grid(row=1, columnspan=80) self._buttonFrame = Frame(self._stage) self._buttonFrame.grid(row=self._height + 100, columnspan=80) self._label = Label(self._buttonFrame, text="") self._label.grid(row=1, column=1) self._flagRemainning = Label(self._buttonFrame, text='Flags left: ' + str(self._flags)) self._flagRemainning.grid(row=1, column=2) self._quitBtn = Button(self._buttonFrame, text='Quit', command=self.quit) self._quitBtn.grid(row=1, column=3) self._labelW = Label(self._bottomFrame, text='W: ') self._labelW.grid(row=1, column=1) self._entryWidth = Entry(self._bottomFrame) self._entryWidth.grid(row=1, column=2) self._labelH = Label(self._bottomFrame, text='H: ') self._labelH.grid(row=2, column=1) self._entryHeight = Entry(self._bottomFrame) self._entryHeight.grid(row=2, column=2) self._entryBomb = Entry(self._bottomFrame) self._entryBomb.grid(row=3, column=2) self._labelB = Label(self._bottomFrame, text='B: ') self._labelB.grid(row=3, column=1) self._applyBtn = Button(self._bottomFrame, text='Play', command=self.play) self._applyBtn.grid(row=4, column=2) self._resetBtn = Button(self._buttonFrame, text='Reset', command=self.resetButton) self._resetBtn.grid(row=1, column=4) self._labelError = Label(self._buttonFrame, text="", fg="red") def createMenuBar(self): self._stage.bind( '<KeyPress-x><KeyPress-y><KeyPress-z><KeyPress-z><KeyPress-y>', self.showMines) menubar = Menu(self._stage) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label="Łatwy", command=lambda: self.reset(8, 8, 1)) filemenu.add_command(label="Średni", command=lambda: self.reset(10, 10, 14)) filemenu.add_command(label="Trudny", command=lambda: self.reset(14, 14, 30)) filemenu.add_separator() filemenu.add_command(label="Rekordy", command=self._fileController.showRecords) filemenu.add_separator() filemenu.add_command(label="Exit", command=self._stage.quit) menubar.add_cascade(label="File", menu=filemenu) self._stage.config(menu=menubar) def showInformationLabel(self, text): filewin = Toplevel(self._stage) labelW = Label(filewin, text=text) labelW.grid(row=1, column=1) def showMines(self, event): for i in range(self._elements): if self._buttons[i].getBomb(): self._buttons[i].config(image=self._special[11]) def createButton(self, stage): self._buttons = [] r = 1 c = 1 for x in range(0, self._elements): self._buttons.append( Field('free', self._buttonFrame, r, c, height=20, width=20, image=self._special[3])) self._buttons[x].grid(row=r + 1, column=c + 1) self._buttons[x].bind('<Button-1>', self.leftClick_w(x)) self._buttons[x].bind('<Button-3>', self.rightClick_w(x)) c += 1 if c == self._width + 1: c = 1 r += 1 def update_clock(self): now = time.time() self._label.configure(text=round(now - self._czas, 1)) if self._state == 'game': self._stage.after(100, self.update_clock) def createBombs(self): i = 0 while i < self._flags: a = random.randint(0, self._elements - 1) if not self._buttons[a].getBomb(): self._buttons[a].setBomb() i += 1 if self._buttons[a].getRow() > 1: self._buttons[a - self._width].setValue() if self._buttons[a].getCol() > 1: self._buttons[a - self._width - 1].setValue() if self._buttons[a].getCol() < self._width: self._buttons[a - self._width + 1].setValue() if self._buttons[a].getRow() < self._height: self._buttons[a + self._width].setValue() if self._buttons[a].getCol() > 1: self._buttons[a + self._width - 1].setValue() if self._buttons[a].getCol() < self._width: self._buttons[a + self._width + 1].setValue() if self._buttons[a].getCol() > 1: self._buttons[a - 1].setValue() if self._buttons[a].getCol() < self._width: self._buttons[a + 1].setValue() def reset(self, c, d, bombs): c = int(c) d = int(d) bombs = int(bombs) if not 2 <= c <= 15 or not 2 <= d <= 15 or not 0 <= bombs <= c * d: raise WrongDataException.WrongDataException("") for i in range(0, self._elements): self._buttons[i].destroy() self._buttons.clear() self._flags = bombs self._labelError.grid_forget() self._flagRemainning.config(text='Flags left : ' + str(self._flags)) self._count = c * d self._width = c self._height = d self._bombs = bombs self._elements = c * d self.createButton(self._stage) for i in range(0, self._elements): self._buttons[i].config(image=self._special[3], text='', state='normal', relief=RAISED) [y.reset() for y in self._buttons] self.createBombs() self._state = 'game' self._czas = time.time() self.update_clock() def play(self): c = self._entryWidth.get() d = self._entryHeight.get() bombs = self._entryBomb.get() try: self.reset(c, d, bombs) except ValueError: self._labelError.grid(row=2, columnspan=5) self._labelError.config(text="Niepoprawne dane") except WrongDataException.WrongDataException: self._labelError.grid(row=2, columnspan=5) self._labelError.config( text="Zla wielkosc pola lub zla lizcba bomb") self._state = 'game' self._czas = time.time() def quit(self): self._fileController.saveScore() self._stage.destroy() def leftClick_w(self, x): return lambda Button: self.leftClick(x) def rightClick_w(self, x): return lambda Button: self.rightClick(x) def leftClick(self, btn): if self._state != 'won': if self._buttons[btn].getBomb( ) == True and self._buttons[btn].getTyp() != 'end': self._buttons[btn].config(image=self._special[9]) self.lost() elif self._buttons[btn].getTyp() == 'free': self._buttons[btn].config( image=self._fields[self._buttons[btn].getValue()]) self._count -= 1 self._buttons[btn].setTyp('value') if self._buttons[btn].getValue() == 0: self.showSafe(btn) self.checkWin() def rightClick(self, btn): if self._state != 'won': if self._buttons[btn].getTyp() == 'free': if self._flags > 0: self._buttons[btn].config(image=self._special[1]) self._flags -= 1 self._count -= 1 self._flagRemainning.config(text='Flags Flags left : ' + str(self._flags)) self._buttons[btn].setTyp('flag') self._buttons[btn].setShown(False) else: self._labelError.grid(row=2, columnspan=5) self._labelError.config(text="Brak flag") elif self._buttons[btn].getTyp() == 'flag': self._buttons[btn].config(image=self._special[10]) self._buttons[btn].setTyp('question') self._flags += 1 self._count += 1 self._flagRemainning.config(text='Flags Flags left : ' + str(self._flags)) self.checkWin() self._labelError.grid_forget() elif self._buttons[btn].getTyp() == 'question': self._buttons[btn].config(image=self._special[3]) self._buttons[btn].setTyp('free') self._buttons[btn].setShown(True) def showSafe(self, x): if self._buttons[x].getRow() > 1: self.leftClick(x - self._width) if self._buttons[x].getCol() > 1: self.leftClick(x - (self._width + 1)) if self._buttons[x].getCol() < self._width: self.leftClick(x - (self._width - 1)) if self._buttons[x].getRow() < self._height: self.leftClick(x + self._width) if self._buttons[x].getCol() > 1: self.leftClick(x + self._width - 1) if self._buttons[x].getCol() < self._width: self.leftClick(x + self._width + 1) if self._buttons[x].getCol() > 1: self.leftClick(x - 1) if self._buttons[x].getCol() < self._width: self.leftClick(x + 1) def checkWin(self): if self._flags == self._count or self._count == 0: self._labelError.grid(row=2, columnspan=5) self._labelError.config(text="Wygrales", fg="green") if self._state != "won": self._state = "won" self._fileController.checkRecord(8, 8, 1, 0, self._width, self._height, self._bombs, self._czas) self._fileController.checkRecord(10, 10, 14, 1, self._width, self._height, self._bombs, self._czas) self._fileController.checkRecord(14, 14, 30, 2, self._width, self._height, self._bombs, self._czas) def lost(self): for i in range(self._elements): if self._buttons[i].getBomb(): self._buttons[i].config(image=self._special[9]) self._buttons[i].setTyp('end') self._labelError.grid(row=2, columnspan=5) self._labelError.config(text="Przegrales", fg="red") self._state = 'lost' def resetButton(self): try: self.reset(self._width, self._height, self._bombs) except ValueError: self.showInformationLabel("Niepoprawne dane") except WrongDataException.WrongDataException: self.showInformationLabel("Zla wielkosc pola lub zla lizcba bomb")
class Main: file = FileController() @staticmethod def opening(): print("verson 1.0") print("Welcome to the Birthday Manager") print("Type help to see a full list of commands") print("© Jcheez") print("") @staticmethod def errorMessage(reason): print("") print("Sudden termination") print(reason) print("Please try again") print("") @staticmethod def addPerson(): """ How this method works. 1. Get the details of the person and birthdate 2. Check that name is not blank and birthday are all numbers 3. Gives a confirmation that data has been added. """ print("") print("Adding a new person to the manager...") print("") name = input("Name of the person: ") day = input("Day of Birthdate: ") month = input("Month of Birthdate: ") year = input("Year of Birthdate: ") if name == "": Main.errorMessage("Reason: Name field cannot be blank.") raise Exception() try: day = int(day) month = int(month) year = int(year) except: Main.errorMessage( "Reason: non numbers entered into day, month or year.") raise ValueError() print(Main.file.addPerson(name, day, month, year)) print("") @staticmethod def help(): print("") print("help --> See a full list of commands available") print("add --> Add a person's birthday to the manager") print("remove --> Remove a person's birthday from the manager") print("view all --> View all the birthdays stored in the manager") print( "filter --> View all the birthdays filtered by a particular month" ) print( "this month --> View all birthdays that occur in the next month") print("quit --> Quit the application") print("") @staticmethod def removePerson(): print("") print("Remove a person from the manager...") name = input("Name of the person: ") if name == "": Main.errorMessage("Reason: Name field cannot be blank.") raise Exception() print(Main.file.removePerson(name)) print("") @staticmethod def viewAllBirthdays(): print("") print("Showing all birthdays...") print("") Main.file.viewNames() print("") @staticmethod def filterBirthdays(): print("") print("Fitering birthdays...") month = input("Month which you will like to filter: ") print("") Main.file.filterBirthdays(month) print("") @staticmethod def filterNextMonthBirthdays(): print("") print("Fitering this month's birthdays...") month_current = datetime.today().month print("") Main.file.filterBirthdays(calendar.month_name[month_current]) print("")
def createSourceEntryFile(dir, groupId): ScriptMonitor.message("Creating sample java class: MainApplication.java"); content = FileController.readFile("templates/java.template"); res = content.replace("{package.name}", groupId+".app;") FileController.writeToFile(res, dir+"/MainApplication.java");
def createLogPropertiesFile(groupId, filepath): ScriptMonitor.message("Creating the log4j file: log4j.properties"); content = FileController.readFile("templates/log.template"); updatedContent = content.replace("{group.id}", groupId); FileController.writeToFile(updatedContent, filepath);
def __init__(self): self.lista = list() self.fileController = FileController() self.indexController = IndexController()
def test_checkNewRecord(self): stage = Tk() fileController = FileController(stage) fileController.checkRecord(2, 2, 2, 1, 2, 2, 2, time.time()-0.1) self.assertEqual(fileController.rekordy[1][1], 0.1)
def __write_to_file__(self): print("Writing to file....") file_controller = FileController() file_controller.write_to_file(DuplicateFileHandler.duplicate)
print('clean') try: shutil.rmtree(config['lookup']) shutil.rmtree(config['stemming']) except: pass if args.stemming: WordCacheInstance.directory = 'stemming' btreeInstance.directory = 'stemming' btreeReverseInstance.directory = 'stemming' if args.add and args.r: if args.query: FC = FileController(stemming=args.stemming) FC.recursiveAdd(args.query) FC.save() else: print('No path given. A path is required') elif args.add: if args.query: FC = FileController(stemming=args.stemming) name = os.path.split(args.query)[1] FC.add(name, args.query) FC.save() else: print('No path given. A path is required') if args.queryloop: queryloop(args.stemming)
self.filename_text.insert(fname) def main(): print 'Hello, world!' def outputMenu(): print("Welcome to the AlmostUnlimitedStorage Cloud\n") print("Type UP to upload a new video\n") print( "Type DOWN to download a video that has already been uploaded to our cloud\n" ) print("Type QUIT to quit\n") print 'Type CLEAR to clear saved videos\n' if __name__ == '__main__': #db = Backend() #db.init #sys.exit(app.exec_()) app = QtGui.QApplication(sys.argv) app.setStyleSheet(qdarkstyle.load_stylesheet()) unlimited_ui = UnlimitedUi() sys.exit(app.exec_()) # File Controller with Dict from JSON file file_controller = FileController() file_controller.process_json()