def state_one(self): state_one = pygame.image.load('state_one.bmp') back_button_parameters = Rect(35, 610, 210, 60) next_button_parameters = Rect(925, 440, 110, 75) self.s.game_display.blit(state_one, (0, 0)) e1 = Entry(440,445,440,50) e1.draw(self.s.game_display) self.s.refresh_background() while self.run_game: for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN: if back_button_parameters.collidepoint(event.pos): self.state_zero() elif next_button_parameters.collidepoint(event.pos): self.state_two(e1.text) elif e1.entry.collidepoint(event.pos): e1.active = not e1.active # e1.type(event) else: e1.active = False if event.type == pygame.KEYDOWN: e1.type(event) if event.type == pygame.QUIT: self.run_game = False self.s.game_display.blit(state_one, (0, 0)) e1.draw(self.s.game_display) pygame.display.update() pygame.quit() quit()
def test_cancel(self): tref = Entry(lambda x: x, (1,), {}) assert not tref.canceled assert not tref.cancelled tref.cancel() assert tref.canceled assert tref.cancelled
def updateEntry(addressBook): name = input('What is the name for the updated entry? ') name = name.lower() #converts name for storage name = name.capitalize() #converts name for dict if name not in addressBook: print('Name not in the address book\n') else: #menu print('select which item you want to update.') print('1 - update address') print('2 - update phone') print('5 - EXIT(back to Main Menu)') choice = int(input('please enter a 1 or 2 or 5: ')) while choice != 5: if choice == 1: address = input('Enter their address here: ') x = Entry.AddressEntry(name, address, addressBook[name].phone) addressBook[name] = x elif choice == 2: phone = input('please enter a phone number here: ') x = Entry.AddressEntry(name,addressBook[name].address, phone) addressBook[name] = x choice = int(input('please enter a 1,2 or 5(main menu)'))
def when_get_signal("plus"): while not (start == finish): if ((start % multiple) == 0): plus1 = start # 시작 숫자를 plus1에 대입 plus2 += plus1 # plus1을 plus2에 더하기 start += 1 Entry.write_text(plus2)
def testSentenceOneLines(self): """Parse one sentence in several lines. Lines have to be appended.""" lines = """How are you?""" e = Entry(lines) self.assertEqual(["How are you?"], e.getSentences())
def test_cancel(self): tref = Entry(lambda x: x, (1,), {}) self.assertFalse(tref.canceled) self.assertFalse(tref.cancelled) tref.cancel() self.assertTrue(tref.canceled) self.assertTrue(tref.cancelled)
def Run(): reg = Entry.AskIsRegistered() # if reg: user = Entry.AskLoginPass() # else: user = Entry.Register() # print("Welcome, %s\n" % user) # userData = DBAccess.GetDateOfBirth(user) # recover = BioMenu.AskIsRecoverResults(userData[0]) if recover: while 1: res = BioMenu.AskRecoverVersion(userData[0]) BioMenu.RecoverVersion(res) if not BioMenu.AskIsRecoverResults(userData[0]): break if BioMenu.AskBuildNew(): BioMenu.AskBiorhythms(userData) else: BioMenu.AskBiorhythms(userData) # print("До свидания, %s" % user)
def test_cancel(self): tref = Entry(lambda x: x, (1, ), {}) assert not tref.canceled assert not tref.cancelled tref.cancel() assert tref.canceled assert tref.cancelled
def test_cancel(self): tref = Entry(lambda x: x, (1, ), {}) self.assertFalse(tref.canceled) self.assertFalse(tref.cancelled) tref.cancel() self.assertTrue(tref.canceled) self.assertTrue(tref.cancelled)
def when_get_signal("number"): while not (start == finish): # 시작 숫자와 끝 숫자가 같을 때 까지 반복 if ((start % multiple) == 0): # 시작 숫자 ÷ 끝 숫자의 나머지가 0이라면 number += 1 # 변수 number에 +1 start += 1 # 시작 숫자 +1 number = (number - 1) Entry.write_text(number)
def testTokensSmiley(self): """Get tokens comprising smileys""" line = "This should work :)" e = Entry(line) self.assertEqual(["This","should","work",":)"], e.getTokens(line)) line = "This should work too :)." self.assertEqual(["This","should","work","too",":)","."], e.getTokens(line)) line = ":D" self.assertEqual([":D"], e.getTokens(line))
def parse(self, journal): """Parses a journal that's stored in a string and returns a list of entries""" # Entries start with a line that looks like 'date title' - let's figure out how # long the date will be by constructing one date_length = len(datetime.today().strftime(self.config['timeformat'])) # Initialise our current entry entries = [] current_entry = None for line in journal.splitlines(): try: # try to parse line as date => new entry begins new_date = datetime.strptime(line[:date_length], self.config['timeformat']) # parsing successfull => save old entry and create new one if new_date and current_entry: entries.append(current_entry) current_entry = Entry.Entry(self, date=new_date, title=line[date_length + 1:]) except ValueError: # Happens when we can't parse the start of the line as an date. # In this case, just append line to our body. current_entry.body += line + "\n" # Append last entry if current_entry: entries.append(current_entry) for entry in entries: entry.parse_tags() return entries
def new_entry(self, raw, date=None, sort=True): """Constructs a new entry from some raw text input. If a date is given, it will parse and use this, otherwise scan for a date in the input first.""" raw = raw.replace('\\n ', '\n').replace('\\n', '\n') # Split raw text into title and body title_end = len(raw) for separator in ["\n", ". ", "? ", "! "]: sep_pos = raw.find(separator) if 1 < sep_pos < title_end: title_end = sep_pos title = raw[:title_end + 1] body = raw[title_end + 1:].strip() if not date: if title.find(":") > 0: date = self.parse_date(title[:title.find(":")]) if date: # Parsed successfully, strip that from the raw text title = title[title.find(":") + 1:].strip() if not date: # Still nothing? Meh, just live in the moment. date = self.parse_date("now") entry = Entry.Entry(self, date, title, body) self.entries.append(entry) if sort: self.sort() return entry
def open(self): filenames = [os.path.join(self.config['journal'], "entries", f) for f in os.listdir(os.path.join(self.config['journal'], "entries"))] self.entries = [] for filename in filenames: if os.path.isdir(filename): continue with open(filename, 'rb') as plist_entry: try: dict_entry = plistlib.readPlist(plist_entry) except self.PLIST_EXCEPTIONS: pass else: try: timezone = pytz.timezone(dict_entry['Time Zone']) except (KeyError, pytz.exceptions.UnknownTimeZoneError): timezone = tzlocal.get_localzone() date = dict_entry['Creation Date'] date = date + timezone.utcoffset(date, is_dst=False) raw = dict_entry['Entry Text'] sep = re.search("\n|[\?!.]+ +\n?", raw) title, body = (raw[:sep.end()], raw[sep.end():]) if sep else (raw, "") entry = Entry.Entry(self, date, title, body, starred=dict_entry["Starred"]) entry.uuid = dict_entry["UUID"] entry.tags = [self.config['tagsymbols'][0] + tag for tag in dict_entry.get("Tags", [])] self.entries.append(entry) self.sort()
def __init__(self, master, dispatcher=None, prefs=None, playCmdSounds=False, summaryLen=10, helpURL=None, helpText=None, width=20, **kargs): self.dispatcher = dispatcher self.summaryLen = int(summaryLen) self.cmdDoneSound = _getSound(playCmdSounds, prefs, "Command Done") self.cmdFailedSound = _getSound(playCmdSounds, prefs, "Command Failed") self.tempIDGen = RO.Alg.IDGen(1, sys.maxsize) Tkinter.Frame.__init__(self, master, **kargs) self.displayWdg = Entry.StrEntry( master=self, readOnly=True, width=width, helpURL=helpURL, ) self.displayWdg.pack(expand="yes", fill="x") self.clear() # bind to catch events self.helpText = helpText if not helpText: tl = self.winfo_toplevel() tl.bind("<<EntryError>>", self.handleEntryError) tl.bind("<Enter>", self.handleEnter) tl.bind("<Leave>", self.handleLeave)
def test_handle_error(self): from datetime import datetime on_error = Mock(name='on_error') s = Timer(on_error=on_error) with patch('kombu.async.timer.to_timestamp') as tot: tot.side_effect = OverflowError() s.enter_at(Entry(lambda: None, (), {}), eta=datetime.now()) s.enter_at(Entry(lambda: None, (), {}), eta=None) s.on_error = None with pytest.raises(OverflowError): s.enter_at(Entry(lambda: None, (), {}), eta=datetime.now()) on_error.assert_called_once() exc = on_error.call_args[0][0] assert isinstance(exc, OverflowError)
def staff(): create_entry_form = CreateEntryForm(request.form) if request.method == 'POST' and create_entry_form.validate(): entries_dict = {} db = shelve.open('storage.db', 'c') try: entries_dict = db['Entries'] except: print("Error in retrieving Users from storage.db.") entry = Entry.Entry(create_entry_form.cost_category.data, create_entry_form.expenses.data) entries_dict[entry.get_entry_id()] = entry db['Entries'] = entries_dict # Test codes entries_dict = db['Entries'] entry = entries_dict[entry.get_entry_id()] print(entry.get_cost_category(), "was stored in storage.db successfully with entry_id ==", entry.get_entry_id()) db.close() session['entry_created'] = entry.get_cost_category() return redirect(url_for('retrieve_entries')) return render_template("staff.html", form=create_entry_form)
def new_entry(self, raw, date=None, sort=True): """Constructs a new entry from some raw text input. If a date is given, it will parse and use this, otherwise scan for a date in the input first.""" raw = raw.replace('\\n ', '\n').replace('\\n', '\n') starred = False # Split raw text into title and body sep = re.search("\n|[\?!.]+ +\n?", raw) title, body = (raw[:sep.end()], raw[sep.end():]) if sep else (raw, "") starred = False if not date: if title.find(": ") > 0: starred = "*" in title[:title.find(": ")] date = jrnl_time.parse( title[:title.find(": ")], default_hour=self.config['default_hour'], default_minute=self.config['default_minute']) if date or starred: # Parsed successfully, strip that from the raw text title = title[title.find(": ") + 1:].strip() elif title.strip().startswith("*"): starred = True title = title[1:].strip() elif title.strip().endswith("*"): starred = True title = title[:-1].strip() if not date: # Still nothing? Meh, just live in the moment. date = jrnl_time.parse("now") entry = Entry.Entry(self, date, title, body, starred=starred) entry.modified = True self.entries.append(entry) if sort: self.sort() return entry
def addEntry(self, data): name = data[0] if self.getEntry(name) is None: # add a new entry self.data.append( Entry(data[0].title(), data[1], data[2], data[3], self.name)) else: print("Error: name exists already in your list")
def parse_editable_str(self, edited): """Parses the output of self.editable_str and updates it's entries.""" # Method: create a new list of entries from the edited text, then match # UUIDs of the new entries against self.entries, updating the entries # if the edited entries differ, and deleting entries from self.entries # if they don't show up in the edited entries anymore. date_length = len(datetime.today().strftime(self.config['timeformat'])) # Initialise our current entry entries = [] current_entry = None for line in edited.splitlines(): # try to parse line as UUID => new entry begins line = line.rstrip() m = re.match("# *([a-f0-9]+) *$", line.lower()) if m: if current_entry: entries.append(current_entry) current_entry = Entry.Entry(self) current_entry.modified = False current_entry.uuid = m.group(1).lower() else: try: new_date = datetime.strptime(line[:date_length], self.config['timeformat']) if line.endswith("*"): current_entry.starred = True line = line[:-1] current_entry.title = line[date_length + 1:] current_entry.date = new_date except ValueError: if current_entry: current_entry.body += line + "\n" # Append last entry if current_entry: entries.append(current_entry) # Now, update our current entries if they changed for entry in entries: entry.parse_tags() matched_entries = [e for e in self.entries if e.uuid.lower() == entry.uuid] if matched_entries: # This entry is an existing entry match = matched_entries[0] if match != entry: self.entries.remove(match) entry.modified = True self.entries.append(entry) else: # This entry seems to be new... save it. entry.modified = True self.entries.append(entry) # Remove deleted entries edited_uuids = [e.uuid for e in entries] self._deleted_entries = [e for e in self.entries if e.uuid not in edited_uuids] self.entries[:] = [e for e in self.entries if e.uuid in edited_uuids] return entries
def __init__(self, master): InputContFrame.InputContFrame.__init__(self, master, stateTracker=None) gr = Gridder.Gridder(master=self) self.wdg1 = Entry.StrEntry(self) gr.gridWdg("Widget 1", self.wdg1) self.wdg2 = Entry.FloatEntry(self) gr.gridWdg("Widget 2", self.wdg2) stdPresets = dict( default1={ "Widget 1": "value 1", "Widget 2": "1.1", }, default2={ "Widget 1": "value 2", "Widget 2": "2.2", }, ) self._inputCont = RO.InputCont.ContList(conts=[ RO.InputCont.WdgCont( name='Widget 1', wdgs=self.wdg1, ), RO.InputCont.WdgCont( name='Widget 2', wdgs=self.wdg2, ), ], ) self.configWdg = InputContPresetsWdg( master=self, sysName="test", userPresetsDict=userPresetsDict, stdPresets=stdPresets, inputCont=self._inputCont, ) gr.gridWdg("Presets", self.configWdg) gr.allGridded()
def test_handle_error(self): from datetime import datetime scratch = [None] def on_error(exc_info): scratch[0] = exc_info s = Timer(on_error=on_error) with patch('kombu.async.timer.to_timestamp') as tot: tot.side_effect = OverflowError() s.enter_at(Entry(lambda: None, (), {}), eta=datetime.now()) s.enter_at(Entry(lambda: None, (), {}), eta=None) s.on_error = None with self.assertRaises(OverflowError): s.enter_at(Entry(lambda: None, (), {}), eta=datetime.now()) exc = scratch[0] self.assertIsInstance(exc, OverflowError)
def test_call(self): scratch = [None] def timed(x, y, moo='foo'): scratch[0] = (x, y, moo) tref = Entry(timed, (4, 4), {'moo': 'baz'}) tref() self.assertTupleEqual(scratch[0], (4, 4, 'baz'))
def when_press_key("space"): if ((n1 < n2) or (n1 < n3)): Entry.send_signal("n1") if ((n2 < n1) or (n2 < n3)): Entry.send_signal("n2") if ((n3 < n1) or (n3 < n2)): Entry.send_signal("n3")
def loadSongs(LIST_NAME, entries_list): """Loads the list of names from a text file, one per line.""" with open(LIST_NAME + ".txt", "r", encoding='utf-8') as file: for line in file: entry = Entry() # line = "Player: Artist - Song\n" line = line.strip() # temp = ["Player", "Artist - Song"] temp = line.split(": ", maxsplit=1) entry.player = temp[0] # temp2 = ["Artist", "Song"] temp2 = temp[1].split(" - ", maxsplit=1) entry.artist = temp2[0] entry.song = temp2[1] entries_list.append(entry) return entries_list
def InstanceEntry (self, cfg_key, type, **kwargs): # Instance an Entry entry = Entry (cfg_key, type, self._cfg, **kwargs) txt = str(entry) # Check whether there is a related error if cfg_key in self.errors.keys(): msg, val = self.errors[cfg_key] if val: txt += '<div class="error"><b>%s</b>: %s</div>' % (val, msg) else: txt += '<div class="error">%s</div>' % (msg) return txt
def body(self, master): Label.StrLabel(master=master, text="Rename Preset:").grid(row=0, column=0, columnspan=5) # Tkinter.Label(master, text="Name:").grid(row=1, column=0) self.oldNameWdg = OptionMenu.OptionMenu( master=master, items=self._currNameList, ) self.newNameWdg = Entry.StrEntry(master) self.oldNameWdg.grid(row=1, column=1) self.newNameWdg.grid(row=1, column=2) return self.newNameWdg # return the item that gets initial focus
def load_from_csv(csv_reader): for line in csv_reader: if len(line) == 9: if line[6] == '#Saldo końcowe': continue try: entry = Entry.create_from_csv(line) repository = entry.repository() repository.add(entry) except Exception as ex: if str(ex) == 'MetaRepository not implemented': pass else: raise ex
def InstanceCheckbox (self, cfg_key, default=None, quiet=False): try: tmp = self._cfg[cfg_key].value.lower() if tmp in ["on", "1", "true"]: value = '1' else: value = '0' except: value = None if value == '1': entry = Entry (cfg_key, 'checkbox', quiet=quiet, checked=value) elif value == '0': entry = Entry (cfg_key, 'checkbox', quiet=quiet) else: if default == True: entry = Entry (cfg_key, 'checkbox', quiet=quiet, checked='1') elif default == False: entry = Entry (cfg_key, 'checkbox', quiet=quiet) else: entry = Entry (cfg_key, 'checkbox', quiet=quiet) return entry
def addEntry(addressBook): name = input("\nWhat is the name for the new entry? ") name = name.capitalize() if name in addressBook: print("\nSorry, there is already an entry for ", name, "\n") else: email = input("\nWhat is their address? ") pho_num = input("\nWhat is their phone number?") x = Entry.AddressEntry(name, email, pho_num) addressBook[name] = x return
def body(self, master): Label.StrLabel(master=master, text="Save This Preset As:").grid(row=0, column=0, columnspan=5) # Tkinter.Label(master, text="Name:").grid(row=1, column=0) self.nameEntry = Entry.StrEntry(master) self.currNameWdg = OptionMenu.OptionMenu( master=master, items=self._currNameList, label="", callFunc=self._doOptionMenu, ) self.nameEntry.grid(row=1, column=1) self.currNameWdg.grid(row=1, column=2) return self.nameEntry # return the item that gets initial focus
def get_first_word_of(self, to_find): # Returns the first instance of a word # in the iWeb corpus where # the word is that word. if type(to_find) is str: db = dataset.connect(self.db_url) results = db.query("SELECT * FROM entries WHERE word LIKE '" + to_find + "' LIMIT 1") for result in results: return Entry(int(result["word_id"]), result["word"], result["lemma"], result["pos"]) return None else: raise TypeError("to_find should be of type str")
def _get_entries(self, stmt): entries = [] row = stmt.next() while row is not None: e = Entry.Entry() r = [ row.get_string(), row.get_date(), row.get_date(), row.get_string(), row.get_string(), row.get_string(), row.get_float(), row.get_float() ] e.from_db(r) entries.append(e) row = stmt.next() return entries
def get_first_lemma_of(self, to_find): # Returns the first instance of a word # in the iWeb corpus where # the lemma is that word. # # Thus, searching for "potatoes" will not # return a value because the lemma of # "potatoes" is "potato" if type(to_find) is str: db = dataset.connect(self.db_url) results = db.query("SELECT * FROM entries WHERE lemma LIKE '" + to_find + "' LIMIT 1") for result in results: return Entry(int(result["word_id"]), result["word"], result["lemma"], result["pos"]) return None else: raise TypeError("to_find should be of type str")
def testSentenceOneMail2(self): "Parse one sentence containing a mail with a dotted name" line = "The mail of my developer is [email protected]." e = Entry(line) self.assertEqual([line], e.getSentences())
def testSentenceOneMail(self): "Parse one sentence containing mail" line = "The mail of my developer is [email protected]." e = Entry(line) self.assertEqual([line], e.getSentences())
def testSentenceOneAcronym(self): "Parse one sentence containing acronyms" e = Entry("A.I. means Artificial Intelligence.") self.assertEqual(["A.I. means Artificial Intelligence."], e.getSentences())
def testSentenceOneSmiley(self): "Parse one sentence containing a smiley" e = Entry("Eheh :) this is cool") self.assertEqual(["Eheh :) this is cool"], e.getSentences())
def testSentenceOneUrl(self): "Parse one sentence containing an URL" e = Entry("The site http://pyector.googlecode.com/ is great!") self.assertEqual(["The site http://pyector.googlecode.com/ is great!"], e.getSentences())
def testSentenceFour(self): "Separate two sentences" e = Entry("One. Two! Three? Four.") self.assertEqual(["One.","Two!","Three?","Four."], e.getSentences())
def testUsername(self): """Replace user name by '@user@'""" e = Entry("François is the bot master!",username="******") self.assertEqual("@user@ is the bot master!",e.entry) self.assertEqual(["@user@","is","the","bot","master","!"], e.getTokens("@user@ is the bot master!"))
from Entry import * #STEP 1 entry = Entry(description="Methodiek van de informatica") assert entry.get_description() == "Methodiek van de informatica" #STEP 2 entry = Entry(day=200) assert entry.get_day() == 200 #STEP 3 meeting = MeetingEntry(description="Dinner",day=133,start=6,end=10) assert meeting.get_description() == "Dinner" assert meeting.get_day() == 133 assert meeting.get_start_slot() == 6 assert meeting.get_end_slot() == 10 #STEP 4 personal = PersonalEntry(description="Study",day=42,slots=frozenset([1,12,24])) assert personal.get_description() == "Study" assert personal.get_day() == 42 for slot in range(1,24): if (slot == 1) or (slot == 12) or (slot == 24): assert personal.occupies_slot(slot) else: assert not personal.occupies_slot(slot) personal.add_slot(14) for slot in range(1,24): if (slot == 1) or (slot == 12) or (slot == 14) or (slot == 24): assert personal.occupies_slot(slot) else:
def testSentenceWithoutPunctuation(self): "Separate one sentence without punctuation" e = Entry("One") self.assertEqual(["One"], e.getSentences())
def testSentencesOne(self): "Separate only one sentence" e = Entry("One.") self.assertEqual(["One."], e.getSentences())
def testTokensUnicode(self): """Get tokens with accented characters""" line = u"Comment ça va?" e = Entry(line) self.assertEqual([u"Comment",u"ça",u"va",u"?"], e.getTokens(line))
def testTokens(self): """Get the tokens of one sentence""" line = "This sentence is not important." e = Entry(line) self.assertEqual(["This","sentence","is","not","important","."], e.getTokens(line))
def testSentenceTwoSmiley(self): """Parse two sentences: one normal, and one smiley""" line = "What happen with a smiley? :)" e = Entry(line) self.assertEqual(["What happen with a smiley?",":)"],e.getSentences())
def testSentenceEndPunctations(self): "Separate one sentence with several end punctuation characters" line = "One..." e = Entry(line) self.assertEqual([line], e.getSentences())
def testBotname(self): """Replace botname by '@bot@'""" e = Entry("Ector is the director!") self.assertEqual("@bot@ is the director!",e.entry) self.assertEqual(["@bot@","is","the","director","!"], e.getTokens("@bot@ is the director!"))
def testSentenceTwo(self): "Separate two sentences" e = Entry("One. Two!") self.assertEqual(["One.","Two!"], e.getSentences()) e = Entry("One. Two") self.assertEqual(["One.","Two"], e.getSentences())
from pygame import * scr = display.set_mode((500,500)) import Entry fiche = """<#ffffff><+b>n<-b><#>ame : <20,20> <#ffffff><+b>f<-b><#>irst <#ffffff><+b>n<-b><#>ame : <20,20> <#ffffff><+b>o<-b><#>ld : <3,3> <#ffffff><+b>y<-b><#>ears""" Entry.get(fiche,'<centered <+i>Entry Test<-i> >',fontsize=15,bgcolor=(20,20,20),fgcolor=(200,100,10))