def __init__(self, title, width, height): self.Title = title self.Height = height self.Width = width self.Screen = pygame.display.set_mode((self.Width, self.Height)) #This is to initialize the framerate (fps) self.Clock = pygame.time.Clock() #This color is a refrence to the color object, in there all different colors are defined self.Color = clr.Color() self.DefaultFont = pygame.font.SysFont(None, 30) #Initialize text messages self.StartText = Text.Text( self.Color.Black, self.DefaultFont, "Make the player move on the screen, up, down, left and right!") self.NextLine = Text.Text( self.Color.Black, self.DefaultFont, "Why do the same thing over and over again when it allready exists!!!" ) #Create all game characters here self.Player1 = c.Component(c.Position(400, 100), "enemy.png") self.Apple = c.Component(c.Position(0, 0), "apple.png") self.AppleCounter = 0 self.Score = Text.Text(self.Color.Black, self.DefaultFont, "Apple Counter: " + str(self.AppleCounter))
def computeTF(self, recompute = True, keysToTokenize = ["articleText"], keyToDisplay = "title"): """Compute the TF for every document in the database. Keys to draw text from to tokenize are given in "keysToTokenize". Optionally, don't recompute.""" ifMap = """function(doc) { if (!('tf' in doc)) emit(doc._id, null); }""" if recompute: results = self.db else: results = self.db.query(ifMap) self.logger.debug("Computing TF") for result in results: try: # if we're recomputing... if (result.find("_design") != -1): continue doc = self.db[result] except AttributeError: # otherwise, just get the key doc = self.db[result["key"]] self.logger.debug("Computing TF: Working on \"%s\"" % doc[keyToDisplay]) # Get the text to use textToTokenize = "" for key in keysToTokenize: textToTokenize += doc[key] + "\n" tokens = Text.tokenize(textToTokenize) numTokens = len(tokens) doc['numTokens'] = numTokens doc['tf'] = Text.get_term_freq(tokens) self.addDocument(doc)
def __init__(self, title, width, height): self.Title = title self.Height = height self.Width = width self.Screen = pygame.display.set_mode((self.Width, self.Height)) #This is to initialize the framerate (fps) self.Clock = pygame.time.Clock() #This color is a refrence to the color object, in there all different colors are defined self.Color = clr.Color() self.DefaultFont = pygame.font.SysFont(None, 30) #Initialize text messages self.StartText = Text.Text(self.Color.Black, self.DefaultFont, "Welcom to my pygame template!!!") #Initialize the soundprovider self.BackgroundMusic = sp.SoundProvider( "9th_Symphony_Finale_by_Beethoven.mp3") #Set the background music to play self.BackgroundMusic.Play(5) #Create all game characters here self.Player1 = c.Component(c.Position(400, 100), "enemy.png") #Create a button self.ExitButton = button.Button( 300, 250, 50, 200, self.Color.Red, Text.Text(self.Color.Black, self.DefaultFont, "Exit"), lambda: sys.exit()) self.StartButton = button.Button( 600, 250, 50, 200, self.Color.Green, Text.Text(self.Color.Black, self.DefaultFont, "Start"))
def process_inbox(): rv, data = M.search(None, "(UNSEEN)") if rv != 'OK': print "No Messages Found!" return for num in data[0].split(): rv, data = M.fetch(num, '(RFC822)') if rv != 'OK': print "Error getting message ", num return msg = email.message_from_string(data[0][1]) msg = msg.as_string() msgBody = msg[msg.index('<td>') + 4: msg.index('</td>')].strip() M.store(num, '+FLAGS', '\\Deleted') response = "" if(not process.authorized): response = process.authorize(phonenum, msgBody) else: response = process.run(msgBody) if(response.strip() != ""): Text.sendText(response, sender, emailPass, phonenum) else: Text.sendText(msgBody + " was successfully called.", sender, emailPass, phonenum) M.expunge() print "Leaving Box"
def draw_UI(self): for text in self.steadyText: text.kill() self.steadyText.add( Text.steadyText(Settings.FONT, 20, 'SCORE', (255, 255, 255), 175, 5)) self.steadyText.add( Text.steadyText(Settings.FONT, 20, str(self.score), (255, 255, 255), 175, 25)) self.steadyText.add( Text.steadyText(Settings.FONT, 20, 'TIME', (255, 255, 255), 400, 5)) self.steadyText.add( Text.steadyText(Settings.FONT, 20, str(self.gameTimer_tock), (255, 255, 255), 400, 25)) self.steadyText.add( Text.steadyText(Settings.FONT, 20, 'WORLD', (255, 255, 255), 600, 5)) self.steadyText.add( Text.steadyText(Settings.FONT, 20, str(self.level), (255, 255, 255), 620, 25)) self.steadyText.add( Text.steadyText(Settings.FONT, 20, 'COINS', (255, 255, 255), 800, 5)) self.steadyText.add( Text.steadyText(Settings.FONT, 20, str(self.coinAmount), (255, 255, 255), 827, 25)) self.steadyText.add( Text.steadyText(Settings.FONT, 20, 'LIVES', (255, 255, 255), 1000, 5)) self.steadyText.add( Text.steadyText(Settings.FONT, 20, str(self.lives), (255, 255, 255), 1027, 25)) self.steadyText.update()
def main(self): while True: if self.mainScreen: self.reset(0, 3, True) self.screen.blit(self.background, (0, 0)) self.titleText.draw(self.screen) self.titleText2.draw(self.screen) self.enemy1Text.draw(self.screen) self.enemy2Text.draw(self.screen) self.enemy3Text.draw(self.screen) self.enemy4Text.draw(self.screen) self.create_main_menu() elif self.startGame: if len(self.enemies) == 0: currentTime = time.get_ticks() if currentTime - self.gameTimer < 3000: self.screen.blit(self.background, (0, 0)) self.scoreText2 = Text(FONT, 20, str(self.score), GREEN, 85, 5) self.scoreText.draw(self.screen) self.scoreText2.draw(self.screen) self.nextRoundText.draw(self.screen) self.livesText.draw(self.screen) self.livesGroup.update(self.keys) self.check_input() if currentTime - self.gameTimer > 3000: # Move enemies closer to bottom self.enemyPositionStart += 35 self.reset(self.score, self.lives) self.gameTimer += 3000 else: currentTime = time.get_ticks() self.play_main_music(currentTime) self.screen.blit(self.background, (0, 0)) self.allBlockers.update(self.screen) self.scoreText2 = Text(FONT, 20, str(self.score), GREEN, 85, 5) self.scoreText.draw(self.screen) self.scoreText2.draw(self.screen) self.livesText.draw(self.screen) self.check_input() self.allSprites.update(self.keys, currentTime, self.enemies) self.explosionsGroup.update(self.keys, currentTime) self.check_collisions() self.create_new_ship(self.makeNewShip, currentTime) self.update_enemy_speed() if len(self.enemies) > 0: self.make_enemies_shoot() self.boss += 1 elif self.gameOver: currentTime = time.get_ticks() # Reset enemy starting position self.enemyPositionStart = self.enemyPositionDefault self.create_game_over(currentTime) self.boss = 0 display.update() self.clock.tick(60)
def dump(filehandle, text, width, fill, wrap_fill, level): debug("Building output") # # Build the output # debug("Wrapping entry text to " + str(width)) # Remove trailing whitespaces (newlines will be added later) text = text.rstrip() # Dump each line dump = [] for i in text.split('\n'): if (width != 0): w = width - (len(fill) * level) if (w <= 0): dump = [] raise Exceptions.WidthTooSmall("cannot wrap " + "text " + text) if (wrap_fill != ""): dump.extend( Text.wrap(i, w, subsequent_indent=wrap_fill, break_ansi_escapes=False)) else: dump.extend(Text.wrap(i, w, break_ansi_escapes=False)) else: dump.append(i) for j in dump: filehandle.write(fill * level + j + "\n")
def main(): #Display ascii art info.show_art() #Display a menu display_menu() #Prompt the user for input and store it in a variable user_option = int(input("Enter your choice: ")) #Evaluate input while user_option is not 3: if user_option is 1: #Print game board grid.printblankgrid() #Get and print users move print(move.get_move()) elif user_option is 2: #Call the show rules menu from the Text module info.show_rules() else: print("Invalid option, try again!\n") #Show the menu display_menu() #Ask for input again user_option = int(input("Enter your choice: ")) #Display good bye print("Good bye!")
def predict(with_embedding, input_prefix=''): if with_embedding: model_emb = models.load_model('data/out/lstm_model_emb') token2ind, ind2token = text_train.token2ind, text_train.ind2token text_prefix = Text(input_prefix, token2ind, ind2token) pred_emb = ModelPredict(model_emb, text_prefix, token2ind, ind2token, max_len, embedding=True) with open("./lstm_with_embedding_output.txt", 'w') as f: for idx in range(100): print(str(idx + 1) + "/100") f.write(pred.generate_sequence(40, temperature=0.7)) f.write('\n') else: model = models.load_model('lstm_model') token2ind, ind2token = text_train.token2ind, text_train.ind2token text_prefix = Text(input_prefix, token2ind, ind2token) pred = ModelPredict(model, text_prefix, token2ind, ind2token, max_len) with open("./lstm_output.txt", 'w') as f: for idx in range(100): print(str(idx + 1) + "/100") f.write(pred.generate_sequence(40, temperature=0.7)) f.write('\n')
def __init__(self, title, width, height): self.Title = title self.Height = height self.Width = width self.Screen = pygame.display.set_mode((self.Width, self.Height)) #This is to initialize the framerate (fps) self.Clock = pygame.time.Clock() #This color is a refrence to the color object, in there all different colors are defined self.Color = clr.Color() self.DefaultFont = pygame.font.SysFont(None,30) #Initialize text messages self.InfoText = Text.Text(self.Color.Red, self.DefaultFont, "COUNT TO 10 | Click the button to increment the counter and finish the game!!!") #Create a button self.CountButton = button.Button(100,250, 50,200, self.Color.Yellow, Text.Text(self.Color.Black, self.DefaultFont, "Click me!")) #Initialize the counter to 0 self.Counter = 0 #Store the counter in a text object self.CounterText = Text.Text(self.Color.Black, self.DefaultFont, str(self.Counter))
def preprocess(self, text: str) -> List[str]: text = txt.expand_contractions( txt.strip_additions( txt.resurrect_expletives(text))) lemmas = tkn.lemmatize( tkn.drop_stopwords( tkn.tokenize(text))) return lemmas
def updateHealthBar(self): currentHealth = self.health size = 2 if currentHealth <= 0: currentHealth = 0 Text.printAchievement("hasDied") pygame.draw.rect(self.window, (173,255,47), (10, 920, currentHealth * size, 30 * size)) pygame.draw.rect(self.window, (255, 0, 0), (110 - (100 - currentHealth * 2), 920, (100 - currentHealth) * size, 30 * size))
def render(self, Mcp: Matrix2.Matrix2, Mps: Matrix2.Matrix2, Mcs: Matrix2.Matrix2, camPosition: Vector2.Vector2) -> None: ''' Renders the grid on screen ''' Mcs_inv = Mcs.inv(diag=True) worldLL = Mcs.inv(diag=True) * screenLL + camPosition screenA = Mcs * worldA startX = (Mcs * (Vector2.Vector2(math.ceil(worldLL.x), worldLL.y) - camPosition)).x # metti a posto ghisbiro startY = ( Mcs * (Vector2.Vector2(worldLL.x, math.ceil(worldLL.y)) - camPosition)).y xA, yA = screenA.x, screenA.y # this guys are x and y units in the screen reference currentPos: float = startX currentRealPos: float = math.ceil(worldLL.x) while currentPos <= 1: if self.verbose: Text.renderToScreen(currentPos + .01, -.99, f'{currentRealPos}') OpenGL.GL.glBegin(OpenGL.GL.GL_LINES) OpenGL.GL.glColor3d(self.GRID_COLOR[0], self.GRID_COLOR[1], self.GRID_COLOR[2]) OpenGL.GL.glVertex3d(currentPos, -1, .2) OpenGL.GL.glVertex3d(currentPos, 1, .2) OpenGL.GL.glEnd() currentPos += xA currentRealPos += 1 currentPos = startY currentRealPos: float = math.ceil(worldLL.y) while currentPos <= 1: if self.verbose: Text.renderToScreen(-.99, currentPos + .01, f'{currentRealPos}') OpenGL.GL.glBegin(OpenGL.GL.GL_LINES) OpenGL.GL.glColor3d(self.GRID_COLOR[0], self.GRID_COLOR[1], self.GRID_COLOR[2]) OpenGL.GL.glVertex3d(-1, currentPos, .2) OpenGL.GL.glVertex3d(1, currentPos, .2) OpenGL.GL.glEnd() currentPos += yA currentRealPos += 1
def run(self): with open(self.parameters['ready_text'], "r") as myfile: text2show = myfile.read().replace('\n,', '\n') try: text2show = text2show.replace('NBLOCKS', str(self.parameters['nblocks'])) except: pass try: text2show = text2show.replace( 'NTRIALS', str(len(self.trial_settings) / self.parameters['nblocks'])) except: pass text_screen = Text(self.parameters, self.screen, text2show) text_screen.show() expdata = list() sumacc_mem = list() sumacc_tim = list() blocki = 0 for k, settings in enumerate(self.trial_settings): trial = Trial(settings, self.parameters, self.screen) trialdata = trial.run() expdata.append(trialdata) if 'mem' in settings: sumacc_mem.append(trialdata[2][0]) elif 'timing' in settings: sumacc_tim.append(trialdata[2][0]) if fmod(k + 1, len(self.trial_settings) / self.parameters['nblocks'] ) == 0: # feedback after mini/practice block blocki = blocki + 1 dbstop() avgacc_mem = round( float(np.mean(np.asarray(sumacc_mem))) * 100.0) avgacc_tim = float(np.mean(np.asarray(sumacc_tim))) if avgacc_tim < 0.25: timefb = 'underestimated' elif avgacc_tim > 0.25: timefb = 'overestimated' else: timefb = 'correctly estimated' text2show = ('This was block ' + str(blocki) + ' of ' + str(self.parameters['nblocks']) + '\n\nYour memory/search accuracy was ' + str(avgacc_mem) + '\n\nOn average you ' + timefb + ' the delays' + '\n\nPress a button to continue') text_screen = Text(self.parameters, self.screen, text2show) text_screen.show() self._finished = True self.output = expdata
def process_inbox(): file = open("directory.txt", "r+") directory = file.read().strip() rv, data = M.search(None, "(UNSEEN)") if rv != "OK": print "No Messages Found!" return for num in data[0].split(): rv, data = M.fetch(num, "(RFC822)") if rv != "OK": print "Error getting message ", num return msg = email.message_from_string(data[0][1]) msg = msg.as_string() msgBody = msg[msg.index("<td>") + 4 : msg.index("</td>")].strip() M.store(num, "+FLAGS", "\\Deleted") print msgBody if msgBody[:2] == "cd": print msgBody.split(" ")[1] directory += msgBody.split(" ")[1] open("directory.txt", "w").close() if directory[-1] != "/": directory += "/" file.write(directory) file.close() response = "" if msgBody[:2] != "cd": command = str("cd " + str(directory) + "; " + msgBody) print command response = subprocess.check_output(command, shell=True) print response if response.strip() != "": Text.sendText(response) else: Text.sendText(msgBody + " was successfully called.") M.expunge() print "Leaving Box"
def __init__(self, window_width, window_height, dark_color, light_color): self.light_color = light_color self.dark_color = dark_color self.title = Text.Text("Laws of Reflection", (window_width // 2, window_height // 2 - 170), light_color, 60) self.author_text = Text.Text("A game by Michael Rainsford Ryan", (window_width // 2, window_height // 2 - 100), light_color, 20) self.continue_text = Text.Text("press space to play", (window_width // 2, window_height // 2 + 100), dark_color, 30) self.twitter_text = Text.Text("Twitter: @MichaelRainRyan", (window_width // 2, window_height // 2 + 260), dark_color, 18)
def useItem(player, item, window): if item.strengthBoost > 0: Text.printAchievement("drankStrengthPotion") elif item.healthRegen > 0: Text.printAchievement("drankHealthPotion") player.attackDamage = player.attackDamage + item.strengthBoost if player.health + item.healthRegen >= 100: player.health = 100 else:player.health = player.health + item.healthRegen if item.isPotion: drink_potion.play()
def create_text(self): self.titleText = Text(FONT, 50, 'Space Invaders', WHITE, 164, 155) self.titleText2 = Text(FONT, 25, 'Press any key to continue', WHITE, 201, 225) self.gameOverText = Text(FONT, 50, 'Game Over', WHITE, 250, 270) self.nextRoundText = Text(FONT, 50, 'Next Round', WHITE, 240, 270) self.enemy1Text = Text(FONT, 25, ' = 10 pts', GREEN, 368, 270) self.enemy2Text = Text(FONT, 25, ' = 20 pts', BLUE, 368, 320) self.enemy3Text = Text(FONT, 25, ' = 30 pts', PURPLE, 368, 370) self.enemy4Text = Text(FONT, 25, ' = ?????', RED, 368, 420) self.scoreText = Text(FONT, 20, 'Score', WHITE, 5, 5) self.livesText = Text(FONT, 20, 'Lives ', WHITE, 640, 5)
def __init__(self, window_width, window_height, text_color): self.thanks_text = Text.Text( "Thanks for Playing!", (window_width // 2, window_height // 2 - 50), text_color, 40) self.follow_text1 = Text.Text( "If you liked this game, consider following", (window_width // 2, window_height // 2 + 20), text_color, 20) self.follow_text2 = Text.Text( "me on Twitter @MichaelRainRyan :)", (window_width // 2, window_height // 2 + 60), text_color, 20) self.exit_text = Text.Text( "press Esc to exit to menu", (window_width // 2, window_height // 2 + 250), text_color, 25)
def update_Text(self, text): passage = text temp = Text.text(passage, self.text_size) if temp.width <= self.frame.width: self.text = temp else: pass
def render(self, Mcp: Matrix2.Matrix2, Mps: Matrix2.Matrix2, Mcs: Matrix2.Matrix2, camPosition: Vector2.Vector2) -> None: super().render(Mcp, Mps, Mcs, camPosition) screenPosition = Mcs * (self.position - camPosition) Text.renderToScreen(screenPosition.x + self.DIFF, screenPosition.y + 2 * self.DIFF, f'X:{self.position.x: .4f}') Text.renderToScreen(screenPosition.x + self.DIFF, screenPosition.y + self.DIFF, f'Y:{self.position.y: .4f}')
def store(text, buffer): id = Text.speech_id(text) txt = _with_root(id, '.txt') mp3 = _with_root(id, '.mp3') txt.write_text(text) mp3.write_bytes(buffer) return mp3
def retrieve(text): id = Text.speech_id(text) mp3 = _with_root(id, '.mp3') if mp3.exists(): return (id, mp3) else: return False
def __init__(this, screen, events, levelManager): ### Universal Componenets this.screen = screen this.events = events this.levelManager = levelManager # Level Properties this.stageText = Text(screen, "", screen.get_width() / 2, 20, (225, 75, 50), 45, "Fonts/Roboto.ttf", True, False, False, False, 0, 0, 0) this.colorList = [(225, 50, 50), (50, 225, 50), (50, 50, 225)] this.textColor = 0 this.textState = 1 # State-Specific Properties this.state = 0 ## Bonus Round this.bonusFrame = 0 this.frameTime = 0 this.textStage = 0 # Objects this.player = Player(screen, events, levelManager) this.bonusEnemies = 0 this.time = 0 this.SetState(0)
def updateBinaries(id, filePath): ext = fs.getExtension(filePath) hexa = bin2hex(filePath) sql = Text.format(UPDATE, id, ext, filePath, hexa) client = mysql.MySQL() client.execute(sql) return
def run_tests(exec_path: str, test_path: str, test_type: str = "int", quite_ecode=None, key=None, dbg=False): """ test_type - can be int, str, float depending on what type of data we use quite_code - if true we check only exit status if false we checking specific exit code such as we write in test file #exitcode 1 programm returned 2, so result of test - FAILED key - this attribute is optional and you should use it only if you parsing strings from programm's output. Basycally this is string's begin Testing file. First of all, parsing given test file, then we executing file with all tests, creating class object where we can find results and then returning it """ test_data = Text.parse_test_file(test_path) number_of_tests = len(test_data) test_list = [] for i in range(len(test_data)): try: args = test_data[i]["args"] # print(f"ARGS {args}") except KeyError: args = "" real_data = exec_file(exec_path, data=test_data[i]["input"], ftype=test_type, key=key, args=args, dbg=dbg) test_output = get_data_from_string(test_data[i]["output"], test_type) test_exitcode = int(test_data[i]["exitcode"]) if not quite_ecode: # If quite_ecode == True we dont mansion on specific exit value # We interested only in exit statue - it can be either passed or failed real_data["exitcode"] = abs(real_data["exitcode"]) > 0 test_exitcode = abs(test_exitcode) > 0 test = Test(real_data["coll_data"], test_output, real_data["exitcode"], test_exitcode, test_data[i]["title"]) test_list.append(test) Tests = TestList(test_list) return Tests
def draw(self): pygame.draw.rect(self.surface, self.bgColor, self.rect, self.width) self.onHover() txt = Text( self.surface, self.text, "Consolas", 30, (255, 255, 255), "center", (self.rect[0] + self.rect[2] / 2, self.rect[1] + self.rect[3] / 2)) txt.draw()
def test_analysis_is_correct(self): text1 = Text("The Ass of my aSs is not my arse") result1 = text1.generate_analysis() self.assertEqual(result1['ass']['position'], [1, 4]) self.assertEqual(result1['ass']['count'], 2) self.assertEqual(result1['arse']['position'], [8]) self.assertEqual(result1['arse']['count'], 1)
def layout(self): self.setbbox(QRectF(0.0, 0.0, self.loWidth(), self.loHeight())) n = self.no() + 1 + self._score.pageFormat()._pageOffset if self.score().styleB(StyleIdx.ST_showPageNumber) and ( self.no() > 0 or self.score().styleB(StyleIdx.ST_showPageNumberOne)): if n & 1: subtype = TEXT.TEXT_PAGE_NUMBER_ODD else: subtype = TEXT.TEXT_PAGE_NUMBER_EVEN if n & 1: style = TEXT.TEXT_STYLE_PAGE_NUMBER_ODD else: style = TEXT.TEXT_STYLE_PAGE_NUMBER_EVEN if self._pageNo == 0: self._pageNo = Text(self.score()) self._pageNo.setParent(self) if subtype != self._pageNo.subtype(): self._pageNo.setSubtype(subtype) self._pageNo.setTextStyle(style) s = QString("%1").arg(n) if self._pageNo.getText() != s: self._pageNo.setText(s) self._pageNo.layout() else: self._pageNo = 0 if self._score.rights: if self._copyright == 0: self._copyright = TextC(self._score.rights) self._copyright.setParent(self) self._copyright.setTextStyle(TEXT.TEXT_STYLE_COPYRIGHT) self._copyright.layout() else: self._copyright = 0
def OnGroupMsgs(message): ''' 监听群组消息''' tmp1 = message tmp2 = tmp1['CurrentPacket'] tmp3 = tmp2['Data'] a = GMess(tmp3) ''' a.FrQQ 消息来源 a.QQGName 来源QQ群昵称 a.FromQQG 来源QQ群 a.FromNickName 来源QQ昵称 a.Content 消息内容 a.MsgSeq 消息ID ''' if 'GroupPic' in str(a.Content): Group.Group(msg=a.Content, QQ=a.FromQQID, GroupID=a.FromQQG) else: Jiance = Text.Check(msg=a.Content) if Jiance['Data']['DetailResult'] == None: Group.Group(msg=a.Content, QQ=a.FromQQID, GroupID=a.FromQQG) else: Group.Block(Jiance['Data']['DetailResult'][0]['EvilLabel'], GroupID=a.FromQQG, MsgSeq=a.MsgSeq, MsgRandom=a.MsgRandom, QQ=a.FromQQID) te = re.search(r'\#(.*)', str(a.Content)) if te == None: return
def __init__(this, screen, events, levelManager, command, commandParameter, txt, x, y, sizeX, sizeY, btnCol, hvrCol, psdCol, txtCol, fadeIn, speed): ### Universal Componenets this.screen = screen # used to display button this.events = events # gets events this.levelManager = levelManager ### Commands this.command = command # button pressed action this.commandParameter = commandParameter # extra button press parameter ### Button Properties this.x = x # x pos this.desiredX = x # used with transitions this.y = y # y pos this.size = (sizeX, sizeY) # size this.txt = txt # text ### Colors this.btnCol = btnCol # button this.hvrCol = hvrCol # hover this.psdCol = psdCol # pressed this.txtCol = txtCol # text ### Transitions this.fadeIn = fadeIn # whether or not to use a transition this.speed = speed # transition speed if (this.fadeIn): this.x = screen.get_width() ### Button State this.hover = False this.pressed = False this.text = Text(screen, this.txt, this.x, this.y - this.size[1]/2 + 7, this.txtCol, 30, "Fonts/Roboto.ttf",True, False, False, False, 0, 0, speed)
def __init__(self, dataSet): self.dataSet = dataSet self.cardType = CardType.createType(self.generateList('type'), self.model) self.cardTypes = CardTypes.createTypes(self.generateList('types'), self.model) self.cmc = Cmc.createCmc(self.generateList('cmc'), self.model) self.colorIdentity = ColorIdentity.createColorIdentity(self.generateList('colorIdentity'), self.model) self.colors = Colors.createColors(self.generateList('colors'), self.model) self.hand = Hand.createHand(self.generateList('hand'), self.model) self.imageName = ImageName.createImageName(self.generateList('imageName'), self.model) self.layouts = Layouts.createLayouts(self.generateList('layout'), self.model) self.legalities = Legalities.createLegalities(self.generateList('legalities'), self.model) self.life = Life.createLife(self.generateList('life'), self.model) self.loyalty = Loyalty.createLoyalty(self.generateList('loyalty'), self.model) self.manaCost = ManaCost.createManaCost(self.generateList('manaCost'), self.model) self.name = Name.createName(self.generateList('name'), self.model) self.names = Names.createNames(self.generateList('names'), self.model) self.power = Power.createPower(self.generateList('power'), self.model) self.printings = Printings.createPrintings(self.generateList('printings'), self.model) self.rulings = Rulings.createRulings(self.generateList('rulings'), self.model) self.source = Source.createSource(self.generateList('source'), self.model) self.starter = Starter.createStarter(self.generateList('starter'), self.model) self.cardSubTypes = CardSubTypes.createSubTypes(self.generateList('subtypes'), self.model) self.cardSuperTypes = CardSuperTypes.createSuperTypes(self.generateList('supertypes'), self.model) self.text = Text.createText(self.generateList('text'), self.model) self.toughness = Toughness.createToughness(self.generateList('toughness'), self.model)
def _renderui(self): black = pygame.Surface((256,64)) self._screen.blit(self._getzoom(black), (0,0)) for i in range(len(self._lifetxt)): self._screen.blit(self._getzoom(self._lifetxt[i]), ((23+i)*8*self._zoom, 16*self._zoom)) self._screen.blit(self._getzoom(self._atxt), ((19)*8*self._zoom, 16*self._zoom)) self._screen.blit(self._getzoom(self._btxt), ((16)*8*self._zoom, 16*self._zoom)) ul = self._getzoom(self._uibox['ul']) ur = self._getzoom(self._uibox['ur']) br = self._getzoom(self._uibox['br']) bl = self._getzoom(self._uibox['bl']) v = self._getzoom(self._uibox['v']) h = self._getzoom(self._uibox['h']) for i in range(2): self._screen.blit(ul, ((3*i+15)*8*self._zoom, 2*8*self._zoom)) self._screen.blit(ur, ((3*i+17)*8*self._zoom, 2*8*self._zoom)) self._screen.blit(br, ((3*i+17)*8*self._zoom, 5*8*self._zoom)) self._screen.blit(bl, ((3*i+15)*8*self._zoom, 5*8*self._zoom)) self._screen.blit(h, ((3*i+16)*8*self._zoom, 5*8*self._zoom)) for j in range(4): self._screen.blit(v, ((3*i+2*(j%2)+15)*8*self._zoom, (j/2+3)*8*self._zoom)) if self._inventory.sword > 0: self._screen.blit(self._getzoom(self._swordsprite), (19*8*self._zoom, 3*8*self._zoom)) self._screen.blit(self._getzoom(self._uirupee), (11*8*self._zoom, 2*8*self._zoom)) self._screen.blit(self._getzoom(self._uikey), (11*8*self._zoom, 4*8*self._zoom)) self._screen.blit(self._getzoom(self._uibomb), (11*8*self._zoom, 5*8*self._zoom)) rupees = Text.get(('X' if self._inventory.rupees < 100 else '')+str(self._inventory.rupees)) for i in range(len(rupees)): self._screen.blit(self._getzoom(rupees[i]), ((i+12)*8*self._zoom,(2)*8*self._zoom)) keys = Text.get('X'+self._inventory.keystr) for i in range(len(keys)): self._screen.blit(self._getzoom(keys[i]), ((i+12)*8*self._zoom,(4)*8*self._zoom)) bombs = Text.get('X'+str(self._inventory.bombs)) for i in range(len(bombs)): self._screen.blit(self._getzoom(bombs[i]), ((i+12)*8*self._zoom,(5)*8*self._zoom)) maprect = pygame.Surface((8*8, 8*4)) maprect.fill((100,100,100)) self._screen.blit(self._getzoom(maprect), (2*8*self._zoom, 2*8*self._zoom)) for i in range(self._pc.maxhp/16): heart = self._fullheart if self._pc.hp > i*16 and self._pc.hp <= i*16+8: heart = self._halfheart elif self._pc.hp <= i*16: heart = self._emptyheart self._screen.blit(self._getzoom(heart), ((22+i%8)*8*self._zoom, (6-i/8)*8*self._zoom))
def _parseline(node): x = int(node.get('x', '0')) y = int(node.get('y', '0')) txt = Text.get(node.get('value', '')) tiles = [] for i in range(len(txt)): tiles.append(Tile.Tile((x+i*8), y, txt[i])) return tiles
def process_inbox(): #file = open('directory.txt', 'r+') #directory = file.read().strip(); rv, data = M.search(None, "(UNSEEN)") if rv != 'OK': print "No Messages Found!" return for num in data[0].split(): rv, data = M.fetch(num, '(RFC822)') if rv != 'OK': print "Error getting message ", num return msg = email.message_from_string(data[0][1]) msg = msg.as_string() msgBody = msg[msg.index('<td>') + 4 : msg.index('</td>')].strip() M.store(num, '+FLAGS', '\\Deleted') response = "" if(not process.authorized): response = process.authorize(phonenum, msgBody) else: response = process.run(msgBody); if(response.strip() != ""): Text.sendText(response, sender, emailPass, phonenum) else: Text.sendText(msgBody + " was successfully called.", sender, emailPass, phonenum) M.expunge() print "Leaving Box"
def fieldsFromTable(tab, tableName, fieldPrimary, fieldSecondary): tables = rd.tables() firstRowFlag = True attributes = {} prefix = 'at' i = 0 if fieldSecondary == '': with arcpy.da.SearchCursor(tables[tab], ['id', fieldPrimary]) as cursor: for row in sorted(cursor, key=itemgetter(0)): if firstRowFlag: ref = row[0] fid = 'tc' + str(i).zfill(2) attributes[fid] = row[1] i+=1 firstRowFlag = False elif ref == row[0]: fid = 'tc' + str(i).zfill(2) attributes[fid] = row[1] i+=1 else: break t.writeToFile(tab[:9] + '.xml', tableName, attributes) else: with arcpy.da.SearchCursor(tables[tab], ['id', fieldPrimary, fieldSecondary]) as cursor: for row in sorted(cursor, key=itemgetter(0)): if firstRowFlag: ref = row[0] fid = 'tc' + str(i).zfill(2) attributes[fid] = row[1] + ' (' + row[2] + ')' i+=1 firstRowFlag = False elif ref == row[0]: fid = 'tc' + str(i).zfill(2) attributes[fid] = row[1] + ' (' + row[2] + ')' i+=1 else: break t.writeToFile(tab[:9] + '.xml', tableName, attributes) return attributes
def loadSinks(self): self.sink_list.addSink(Info.init()) self.sink_list.addSink(Buttons.init()) self.sink_list.addSink(Menus.init()) self.sink_list.addSink(Images.init()) self.sink_list.addSink(Layouts.init()) self.sink_list.addSink(Lists.init()) self.sink_list.addSink(Popups.init()) self.sink_list.addSink(Tables.init()) self.sink_list.addSink(Text.init()) self.sink_list.addSink(Trees.init()) self.sink_list.addSink(Frames.init()) self.sink_list.addSink(Tabs.init())
def getPPCInfo(self, text): """Get PPC info from our database from the string given.""" tokens = Text.tokenize(text) documents = [] for token in tokens: try: documents.append(self.db[token]) except couchdb.client.ResourceNotFound: continue return documents
def loadSinks(self): #self.sink_list.addSink(DataTree.init()) #self.sink_list.addSink(RecipeSystemIFACE.init()) self.sink_list.addSink(ADViewerIFACE.init()) self.sink_list.addSink(RecipeViewer.init()) self.sink_list.addSink(FITSStoreFACE.init()) self.sink_list.addSink(DisplayIFACE.init()) self.sink_list.addSink(Info.init()) if False: self.sink_list.addSink(Buttons.init()) self.sink_list.addSink(Menus.init()) self.sink_list.addSink(Images.init()) self.sink_list.addSink(Layouts.init()) self.sink_list.addSink(Lists.init()) self.sink_list.addSink(Popups.init()) self.sink_list.addSink(Tables.init()) self.sink_list.addSink(Text.init()) if False: #preserving originaly order self.sink_list.addSink(Frames.init()) self.sink_list.addSink(Tabs.init())
def generatePreview(self): words = self.strings.getList() sentences = self.generateLesson(words) self.sample.clear() for x in Text.to_lessons(sentences): self.sample.append(x + "\n\n")
def check(): try: process_inbox() except: Text.sendText("Error", sender, emailPass, phonenum)
module_logger.error("contents of rc_d: %s" % rc_d) LocaleLang = 'system' #This will set the locale used by gvr and returns the tuple (txt,loc) # txt is a error message, if any else it will be an empty string. # loc is a string with the locale country code set for gvr, this can be # different from the systems locale. LocaleMesg = utils.set_locale(LocaleLang) try: SetLocale() except Exception,info: module_logger.exception("Problems setting the locale.\n switching to English\nPlease inform the GvR developers about this.") __builtin__.__dict__['_'] = lambda x:x import Text Text.set_summary(LocaleMesg[1])# needed to set summary file used to the current locale Text.set_WBsummary(LocaleMesg[1])# idem for the worldbuilder Text.set_Intro(LocaleMesg[1])# and the intro text # when the frontend is not in sitepackages, as is the case for the org install sys.path.append('gui-gtk') import gvr_gtk # the frontend to use import GvrModel import GvrController def main(handle=None,parent=None): module_logger.debug("main called with: %s,%s" % (handle,parent)) try: # The abstraction layer on top of the gvr stuff
def __init__(self): self._cache = [] self._deathanims = [] self._debugging = False if '-aabbdebug' in sys.argv: self._debugging = True self._startmap = 'ow8-8.map' if '-startm' in sys.argv: self._startmap = sys.argv[sys.argv.index('-startm')+1] self._starthearts = 3 if '-hearts' in sys.argv: self._starthearts = int(sys.argv[sys.argv.index('-hearts')+1]) random.seed() self._SCREENW=256 self._SCREENH=240 self._MAPW=256 self._MAPH=176 self._OFFSET=self._SCREENH-self._MAPH self._UBOUND = pygame.Rect(0, 0, self._MAPW, 8) self._RBOUND = pygame.Rect(self._MAPW, 0, 8, self._MAPH) self._BBOUND = pygame.Rect(0, self._MAPH, self._MAPW, 8) self._LBOUND = pygame.Rect(-8, 0, 8, self._MAPH) self._TEXTSPEED=4 self._sword = None self._haabb = pygame.Rect(0, Tile.HALF, Tile.SIZE, Tile.HALF) self._vaabb = pygame.Rect(2, Tile.HALF, Tile.SIZE-4, Tile.HALF) self._spelunking = 0 self._zoning = None self._zoom = 2 pygame.init() size = width, height = self._SCREENW*self._zoom, self._SCREENH*self._zoom self._screen = pygame.display.set_mode(size) linkpalette = (((0,0,0),(0,0,0)),((128,128,128),(200,76,12)),((192,192,192),(128,208,16)),((255,255,255),(252,152,56))) wss = Spritesheet(bmpres('weapons.bmp')) self._swordsprite = colorReplace(wss.image_at((0,0,8,16), colorkey=(0,0,0)), linkpalette) ssprite = self._swordsprite lssprite = pygame.transform.rotate(ssprite,90) self._swordsprites = {x:y for x,y in zip(DIRECTIONS, (ssprite, pygame.transform.flip(ssprite,False,True), lssprite, pygame.transform.flip(lssprite,True,False)))} self._lifetxt = Text.get('-LIFE-', (216,40,0)) self._btxt = Text.get('Z')[0] self._atxt = Text.get('X')[0] iss = Spritesheet(bmpres('icons.bmp')) heart = iss.image_at((0,0,8,8), colorkey=(0,0,0)) self._fullheart = colorReplace(heart, (((128,128,128), (216,40,0)),)) self._halfheart = colorReplace(iss.image_at((8,0,8,8), colorkey=(0,0,0)), (((128,128,128),(216,40,0)),((255,255,255),(255,227,171)))) self._emptyheart = colorReplace(heart, (((128,128,128),(255,227,171)),)) self._uibox = {} self._uibox['ul'] = colorReplace(iss.image_at((0,8,8,8), colorkey=(0,0,0)), (((128,128,128),(0,89,250)),)) self._uibox['v'] = colorReplace(iss.image_at((8,8,8,8), colorkey=(0,0,0)), (((128,128,128),(0,89,250)),)) self._uibox['h'] = pygame.transform.rotate(self._uibox['v'], 90) self._uibox['ur'] = pygame.transform.flip(self._uibox['ul'], True, False) self._uibox['br'] = pygame.transform.flip(self._uibox['ur'], False, True) self._uibox['bl'] = pygame.transform.flip(self._uibox['ul'], False, True) self._uirupee, self._uikey, self._uibomb = iss.images_at(((0,16,8,8), (8,16,8,8), (16,16,8,8)), colorkey=(0,0,0)) self._uirupee = colorReplace(self._uirupee, (((128,128,128),(255,161,68)),((255,255,255),(255,227,171)))) self._uikey = colorReplace(self._uikey, (((128,128,128),(255,161,68)),)) self._uibomb = colorReplace(self._uibomb, (((192,192,192),(0,89,250)),)) ss = Spritesheet(bmpres('link.bmp')) s = {} s[Direction.UP] = [colorReplace(sp, (((0,0,0),(0,0,0)),((128,128,128),(200,76,12)),((192,192,192),(128,208,16)),((255,255,255),(252,152,56)))) for sp in ss.images_at(((16,0,16,16),(16,16,16,16)), colorkey=(0,0,0))] s[Direction.DOWN] = [colorReplace(sp, (((0,0,0),(0,0,0)),((128,128,128),(200,76,12)),((192,192,192),(128,208,16)),((255,255,255),(252,152,56)))) for sp in ss.images_at(((0,0,16,16),(0,16,16,16)), colorkey=(0,0,0))] s[Direction.LEFT] = [colorReplace(sp, (((0,0,0),(0,0,0)),((128,128,128),(200,76,12)),((192,192,192),(128,208,16)),((255,255,255),(252,152,56)))) for sp in ss.images_at(((32,0,16,16),(32,16,16,16)), colorkey=(0,0,0))] atks = {} atks[Direction.UP] = colorReplace(ss.image_at((16,32,16,16), colorkey=(0,0,0)), linkpalette) atks[Direction.DOWN] = colorReplace(ss.image_at((0,32,16,16), colorkey=(0,0,0)), linkpalette) atks[Direction.LEFT] = colorReplace(ss.image_at((32,32,16,16), colorkey=(0,0,0)), linkpalette) self._pc = Actor(15*8,11*8,2,self._starthearts*16,8,self._vaabb,True,s,atksprites=atks) self._pc.sethitaabb(pygame.Rect(0,0,16,16)) self._pc.addtriumphs((colorReplace(ss.image_at((48,0,16,16), colorkey=(0,0,0)), linkpalette),colorReplace(ss.image_at((48,16,16,16), colorkey=(0,0,0)), linkpalette))) self._pcweapons = [] self._temps = [] self._startport = Portal(self._startmap, 15*8, 10*8, PortalType.Magic) self._start()
def all_weights(text_list): b = burst_analysis(text_list) s = Text.simil_matrix(text_list) return numpy.concatenate((b, s), 1)
def update_all_lines(self, maxWidth, maxHeight): self.lines = Text.get_lines(self.body, maxWidth, 1000000)
M.idle(callback=callback) event.wait() if needsync: event.clear() dosync() config = open('config.txt', 'r') sender = config.readline() emailPass = config.readline() phonenum = config.readline().strip() Text.sendText("Send password.", sender, emailPass, phonenum) M = imaplib2.IMAP4_SSL('imap.gmail.com') M.login(sender, emailPass) M.select("inbox") check() #init thread = Thread(target=idle) event = Event() #start thread.start() time.sleep(60*60)
if __name__ == '__main__': #start = "有川浩" start = "読売新聞" #start = "高橋" #start = "僕は友達が少ない" target = "井上麻里奈" #text = Text.get_wiki(start)[2] ## [id,title,text] #words = Titles.get_titles(text) #print(words) routes = [] result = ["### ERROR ###"] routes.append([start]) target_text = Text.get_wiki(target)[2] ## [id,title,text] target_words = list(set(Titles.get_titles(target_text))) f_name = target + "(text).txt" f = open(f_name, 'w') # 書き込みモードで開く f.write(target_text) # 引数の文字列をファイルに書き込む f.close() # ファイルを閉じる f_name = target + "(words).txt" f = open(f_name, 'w') # 書き込みモードで開く f.write("\n".join(target_words)) # 引数の文字列をファイルに書き込む f.close() # ファイルを閉じる print(target_text) print("================================================================\n") print(target_words)
def update_lines(self, maxWidth, maxHeight): dirt_line_number, dirt_idx = self.get_line_number(self.first_dirt, maxWidth) self.lines = self.lines[:dirt_line_number] + \ Text.get_lines(self.body[self.first_dirt - dirt_idx:], \ maxWidth, self.first_line + maxHeight - dirt_line_number) self.first_dirt = len(self.body)