def teste_colisao_agendas_um_evento_cada(self): futebol = Evento(nome="Futebol", inicio=datetime(2009, 1, 1, 0, 0, 0), fim=datetime(2009, 1, 1, 1, 0, 0)) agenda1 = Agenda() agenda1.adicionar(futebol) agenda2 = Agenda() agenda2.adicionar(futebol) self.assertTrue(agenda1.colide(agenda2))
def __init__(self, wcfg, wfsa): self._wcfg = wcfg self._wfsa = wfsa self._agenda = Agenda(active_container_type=ActiveQueue) self._firstsym = defaultdict( set) # index rules by their first RHS symbol self._item_factory = ItemFactory()
def test_24_exclui_contato(self): a1 = Agenda('Rafael', '11999887766', '*****@*****.**') a1.novo_contato('Ana', '11999888563', '*****@*****.**') a1.novo_contato('Pedro', '1955552222', '*****@*****.**') a1.novo_contato('Mariana', '21145145145', '*****@*****.**') a1.novo_contato('João', '1152525252', '*****@*****.**') a1.contatos[2].adiciona_telefone('45124512', 'casa') exclui01 = a1.apagar_contato('*****@*****.**') exclui02 = a1.apagar_contato('*****@*****.**') exclui03 = a1.apagar_contato('*****@*****.**') exclui04 = a1.apagar_contato('*****@*****.**') resp = [ 'Nenhum contato corresponde ao email dado.', '<Contato: Pedro> excluído com sucesso!', '<Contato: Mariana> excluído com sucesso!', '<Contato: João> excluído com sucesso!' ] msg = 'Método apagar_contato não retornou a mensagem correta' assert exclui01 == resp[0], msg assert exclui02 == resp[1], msg assert exclui03 == resp[2], msg assert exclui04 == resp[3], msg assert not len( a1.contatos ) > 1, 'Pelo menos um dos contatos não foi removido da lista' assert not len( a1.contatos) == 0, 'Apagou mais contatos do que os emails passados' assert a1.contatos[ 0].nome == 'Ana', 'Apagou contatos que não foram pedidos'
def grava_id(self, id_web): if self.tabela == 3: Cliente(self.pk1, self.pk2).grava_id(self.pk1, self.pk2, id_web) elif self.tabela == 4: Agenda(self.pk1).grava_id(self.pk1, id_web) elif self.tabela == 5: Reserva(self.pk1).grava_id(self.pk1, id_web)
def __add(self): check, rst = self.__sanity_check() if check is False: return rst agenda = Agenda(timestamps=self.timestamps, sessID=self.e.get_sessID(), jdID=self.jdID, agendaType=self.detail, startTime=self.e.get_startime(), endTime=self.e.get_endtime(), agendaDetail=self.detail) try: self.db.session.add(agenda) self.db.session.commit() except Exception as err: self.__log_error(err) rst = "您的规划本出了点小问题,这条计划添加失败了..." return rst rst = "已成功帮您添加了" + self.e.day_des_gen() + self.e.time_des_gen() + '开始,预计在' + self.e.day_des_gen(start=False)\ + self.e.time_des_gen(start=False) + '结束的' + self.detail + '计划哈。' return rst
def valida_cliente(self, listaRepetida): retorno = [] retorno.append(1) retorno.append('') if (self.tabela == 4) and (self.acao == 1): agd = Agenda(self.pk1) idCliente = agd.cliente_idweb headers = { 'authorization': self.config.app_token, 'content-type': 'application/json' } url = 'https://api.salaovip.com.br/salao/' + self.config.app_id + '/cliente/' + str( idCliente) r = requests.get(url, headers=headers, timeout=20) if r.json()['code'] == 404: printlog.Info('Cliente de Codigo "' + str(idCliente) + '" e Nome "' + agd.nome_cliente.strip() + '" não existe para o salao id "' + self.config.app_id + '"!') i = 0 while (i != len(listaRepetida)): if listaRepetida[i] == agd.codigo_cliente: retorno[0] = 3 retorno[1] = agd.codigo_cliente break if retorno[0] == 1: if self.atualiza_cliente( self.config.emp_padrao, agd.codigo_cliente, agd.nome_cliente.strip()) == False: retorno[0] = 2 retorno[1] = agd.codigo_cliente return retorno
def get_busy_free_times(events, dStart, dEnd, tStart, tEnd): busytimes = [] freetimes = [] begin = arrow.get(dStart) end = arrow.get(dEnd) time_begin = combine_date_time(begin, arrow.get(tStart)) time_end = combine_date_time(begin, arrow.get(tEnd)) i = 0 for day in arrow.Arrow.range('day',begin,end): busytimes_today = Agenda() for e in events[i:]: if same_date(day.isoformat(), e['start']): busytimes_today.append(Appt.from_iso_date(e['start'],e['end'],'Busy')) #using 'Busy' because we don't want private info any further i = i+1 #we have all busy times for a single day now #lets generate free times from busy times and and append both to their respective arrays timeframe = Appt.from_iso_date(time_begin,time_end,"Free Time") freetimes.append(busytimes_today.complement(timeframe)) busytimes.append(busytimes_today.normalized()) #advance the day to sync with the next iteration time_begin = next_day(time_begin) time_end = next_day(time_end) #return this as a dict of the free and busy times return {"busy":busytimes, "free":freetimes}
def __init__(self, wcfg, wfsa): """ """ self._wcfg = wcfg self._wfsa = wfsa self._agenda = Agenda(active_container_type=ActiveQueue) self._predictions = set() # (LHS, start) self._item_factory = ItemFactory()
def init(self): self.tray = Tray(self) self.head = Head(self) self.agenda = Agenda(self) self.set = Set(self) # qss with open('style.QSS', 'r') as fp: self.setStyleSheet(fp.read()) fp.close()
def test_case_02(self): agenda = Agenda() agenda.add('s') agenda.add('a') agenda.add('c') agenda.add('r') agenda.add('bba') agenda.add('xh') self.assertEqual(agenda, 'test')
def get_idweb(self): if self.tabela == 3: return Cliente(self.pk1, self.pk2).id_web elif self.tabela == 4: return Agenda(self.pk1).id_web elif self.tabela == 5: return Reserva(self.pk1).id_web elif self.tabela == 6: return 0
def test_20_cria_agenda(self): a1 = Agenda('Rafael', '11999887766', '*****@*****.**') assert hasattr( a1, 'meu_contato'), 'Não criou o atributo público corretamente' assert isinstance( a1.meu_contato, Contato), ('meu_contato deve guardar uma instância de Contato') assert hasattr(a1, 'contatos'), 'Não criou o atributo público corretamente' assert a1.contatos == [], ( 'atributo contatos deve ser inicializado como uma lista vazia')
def get_json(self): if self.tabela == 3: return Cliente(self.pk1, self.pk2).parse_to_json() elif self.tabela == 4: return Agenda(self.pk1).parse_to_json() elif self.tabela == 5: return Reserva(self.pk1).parse_to_json() elif self.tabela == 6: return Jornada(self.pk1).parse_to_json() elif self.tabela == 7: return Pontuacao(self.pk1, self.pk2).parse_to_json()
def parse(self, start_symbol, lexicon, grammar, sentence): agenda = Agenda(self.logger) chart = Chart(grammar, agenda, logger=self.logger) chart.introduce_symbol(start_symbol, 0) position = 0 while position < len(sentence) or agenda.size() > 0: if agenda.size() == 0: agenda.add_alternatives( lexicon.get_interpretations(sentence[position]), position) position = position + 1 chart.extend_arcs(agenda.next_constituent())
def test_21_adiciona_contato(self): a1 = Agenda('Rafael', '11999887766', '*****@*****.**') a1.novo_contato('Ana', '11999888563', '*****@*****.**') a1.novo_contato('Pedro', '1955552222', '*****@*****.**') assert len(a1.contatos) == 2, 'A agenda deveria ter 2 contatos' assert a1.contatos[ 0].nome == 'Ana', 'O primeiro contato não está correto' assert a1.contatos[ 1].nome == 'Pedro', 'O segundo contato não está correto' a1.novo_contato('Silvia', '21145145145', '*****@*****.**') assert len(a1.contatos) == 3, 'A agenda deveria ter 3 contatos' assert a1.contatos[ 2].nome == 'Silvia', 'O terceiro contato não está correto'
def solicitar_contacto(): """Esta funcion estara en ejecucion hasta que el usuario no quiera seguir ingresando contactos a la agenda""" while True: print( c.VERDE, c.BOLD, """ A continuacion debes proporcionar informacion sobre el contacto, asegurate de ingresar la info correcta, ejemplo: 8090000000 no es un numero valido en esta agenda el formato debe ser 809-000-0000 y para correos [email protected] """, c.ENDC) opcion = input(c.CYAN + "[DESEAS CONTINUAR?][SI/NO]: " + c.ENDC) if opcion.lower() == 'si': nombre = input(c.VERDE + "[NOMBRE]: " + c.ENDC) apellido = input(c.VERDE + "[APELLIDO]: " + c.ENDC) edad = input(c.VERDE + "[EDAD]: " + c.ENDC) telefono = input(c.VERDE + "[TELEFONO]: " + c.ENDC) email = input(c.VERDE + "[CORREO]: " + c.ENDC) contacto = Contacto(nombre, apellido, edad, telefono, email) if contacto.es_valido(): Agenda(contacto).agregar_registro() opcion2 = input(c.CYAN + "\n" + "[AGREGAR OTRO?][SI/NO]: " + c.ENDC) if opcion2.lower() == 'si': continue elif opcion2.lower() == 'no': print(c.AMARILLO, "\n[!] Regresando al menu anterior...", c.ENDC) sleep(1.5) break else: c.error("Solo puedes responder Si o No.") else: c.error("Contacto no valido, por favor intenta de nuevo!!") elif opcion.lower() == 'no': print(c.AMARILLO, "\n[!] Regresando al menu anterior...", c.ENDC) sleep(1.5) break else: c.error("Solo puedes responder Si o No.")
def test_case_01(self): agenda = Agenda() agenda.add('s') agenda.add('ss') agenda.add('sss') agenda.add('ssss') agenda.add('sssss') self.assertEqual(agenda.search('s'), 5) self.assertEqual(agenda.search('ss'), 4) self.assertEqual(agenda.search('sss'), 3) self.assertEqual(agenda.search('ssss'), 2) self.assertEqual(agenda.search('sssss'), 1) self.assertEqual(agenda.search('ssssss'), 0) self.assertEqual(agenda, 'test')
def __init__(self): self.comandos = { "agregar": self.agregar, "borrar": self.borrar, "mostrar": self.mostrar, "listar": self.listar, "salir": self.salir } archivo = "agenda.db" introduccion = strip(__doc__) self.contacto = Agenda(archivo) if not self.contacto.esarchivo(): introduccion += '\nError: No se pudo abrir "{}"'.format(archivo) REPL(self.comandos, introduccion).ciclo()
def buttons(self): "Création des boutons affichant les numéros de chaque jour du mois" self.buttonlist = [] self.row_numb = 1 # numéro de ligne self.col_numb = 1 # La colonne 0 est réservée pour les boutons affichants les numéros de semaine. for child in self.subframe2.winfo_children(): if child.winfo_class() == 'Button': child.destroy( ) # Destruction des éventuels boutons déjà placés. for i in range(0, len(self.c)): self.sub_buttonlist = [] for i2 in range(0, len(self.c[i])): if self.c[i][ i2] == 0: # Si le jour est absent , itération de la colonne. self.col_numb += 1 if self.col_numb % 8 == 0: # A la huitième colonne, itération de la ligne. self.row_numb += 1 self.col_numb = 1 # Nouvelle ligne : Le numéro de colonne repasse à 1. else: # Création des jours proprement dits : self.button = Button(self.subframe2, text=str(self.c[i][i2]), relief='flat', bd=1, bg='white', padx=10, pady=10) self.button.grid(row=self.row_numb, column=self.col_numb, sticky='nsew') self.sub_buttonlist.append(self.button) self.sub_buttonlist.append(str(self.c[i][i2])) self.buttonlist.append(self.sub_buttonlist) self.sub_buttonlist = [] # Le bouton du jour courant est bleu : if self.c[i][i2] == self.d and self.m == localtime( )[1] and self.y == localtime()[0]: self.button.configure(bg='#357AB7', fg='white') self.row_curweek = self.row_numb # Récupération de la rangée de la semaine en cours self.col_numb += 1 if self.col_numb % 8 == 0: self.row_numb += 1 self.col_numb = 1 self.last_row = self.row_numb # Valeur de la dernière ligne # Appel de la méthode pages du module Agenda. for i in range(0, len(self.buttonlist)): # Création de l'objet "agenda" et configuration de la commande de chaque bouton : self.d = int(self.buttonlist[i][0]['text']) self.agenda = Agenda(self.d, self.m, self.y) self.buttonlist[i][0]['command'] = self.agenda.pages
def cky(cfg, sentence): A = Agenda() for item in cky_axioms(cfg, sentence): A.push(item) while A: item = A.pop() if item.is_complete() or is_nonterminal(item.next): for new in complete(item, A): A.push(new) else: new = scan(item, sentence) if new is not None: A.push(new) A.make_passive(item) return make_forest(A.itercomplete())
def __init__(self): self.agenda = Agenda() self.agenda.adicionaTipo("Celular") self.agenda.adicionaTipo("Residencia") self.agenda.adicionaTipo("Trabalho") self.agenda.adicionaTipo("Fax") self.menu = Menu() self.menu.adicionaopcao("Novo", self.novo) self.menu.adicionaopcao("Altera", self.altera) self.menu.adicionaopcao("Apaga", self.apaga) self.menu.adicionaopcao("Lista", self.lista) self.menu.adicionaopcao("Arquiva", self.arquiva) self.menu.adicionaopcao("Le arquivo", self.le) self.menu.adicionaopcao("Ordena", self.ordena) self.ultimo_nome = None
def __init__(self, bd): """constructor of the main gui Arguments: nombre {string} -- name of the database user contrasena {string} -- name of the database """ self.gui_principal = tk.Tk() self.gui_principal.title("Agenda Lojo v2.0") self.bd = bd self.agenda = Agenda() # Load empty agenda object self.load_data() # load dates for agenda objects self.gui_principal.geometry("600x400") self.load_widgets_principal() self.gui_principal.mainloop()
def run(): agenda = Agenda() with open('contacts.csv', 'r') as f: reader = csv.reader(f) for idx, row in enumerate(reader): if idx == 0: continue agenda.add(row[0], row[1], row[2]) while True: print '''What do you wanna do? [a]Add Contact [u]Update Contact [s]Search Contact [r]Remove Contact [l]List Contacts [e]Exit''' cmd = str(raw_input('=> ')) if cmd == 'a': name = str(raw_input('Contact\'s name: ')) phone = str(raw_input('Contact\'s phone: ')) email = str(raw_input('Contact\'s email: ')) agenda.add(name, phone, email) elif cmd == 'u': name = str(raw_input('Contact\'s name: ')) agenda.search_contact(name) n_name = str(raw_input('New name: ')) n_phone = str(raw_input('New phone: ')) n_email = str(raw_input('New email: ')) agenda.update_contact(name, n_name, n_phone, n_email) elif cmd == 's': name = str(raw_input('Contact\'s name: ')) agenda.search_contact(name) elif cmd == 'r': name = str(raw_input('Contact\'s name: ')) agenda.remove_contact(name) elif cmd == 'l': agenda.list() elif cmd == 'e': break else: print 'Choose a valid action.'
def gui_edita_contacto_modifica(self): """ after checking the entry run an update and reload the application data Returns {void}: after update reload aplication load """ print(self.usu) if self.imput_edit_user.get() != "" and self.input_edit_number.get(): if funciones.comprueba_numero(self.input_edit_number.get()): if not self.bd.if_exists( ("contacto", self.imput_edit_user.get())) and not self.bd.if_exists( ("contacto", self.input_edit_number.get())): ask = messagebox.askyesno( "Alerta", "Estás seguro de que quieres modificar a " + self.usu) if ask: self.bd.update_contacto( "contacto", ("numero", self.input_edit_number.get(), self.usu)) self.bd.update_contacto( "contacto", ("nombre", self.imput_edit_user.get(), self.usu)) self.bd.cursor.execute( "update grupos set contacto_origen = '%s' where contacto_origen like " "'%s'" % (self.imput_edit_user.get(), self.usu)) self.bd.conexion.commit() self.bd.cursor.execute( "update grupos set contacto_miembro = '%s' where contacto_miembro like " "'%s'" % (self.imput_edit_user.get(), self.usu)) self.bd.conexion.commit() self.agenda = Agenda() self.load_data() self.load_Treeview_consulta_pri() self.load_data_treeview_after_update() self.gui_edita_contacto_salir() else: messagebox.showwarning("Error", "Datos ya existen en la agenda") else: messagebox.showwarning("Error", "El teléfono no es válido") else: messagebox.showwarning("Error", "Campos vacíos")
def to_agenda(self, output_path): agenda = Agenda(self.language, self._theme, len(self._speakers)) # opening agenda.append_session( self.opening_session( datetime.datetime(self._year, self._month, self._day, 18, 45))) # prepared session if self.have_prepared_speech: agenda.append_session( self.prepared_session(agenda.current_datetime)) # table topic session agenda.append_session(self.table_topic_session( agenda.current_datetime)) agenda.append_session(self.evaluation_session(agenda.current_datetime)) agenda.dump(output_path)
def __init__(self): self.nomeCaixa = builder.get_object("nomeCaixa") self.telefoneCaixa = builder.get_object("telefoneCaixa") self.grade = builder.get_object("grade") self.lstagenda = builder.get_object("lstagenda") self.lb_status = builder.get_object("lb_status") self.conexao = sqlite3.connect("banco.db") self.cursor = self.conexao.cursor() self.ag = Agenda() sql_busca = "select * from agenda" self.cursor.execute(sql_busca) busca_agenda = self.cursor.fetchall() self.lstagenda.clear() for i in busca_agenda: cod = str(i[0]) nome = i[1] telefone = i[2] lista_pergunta = (cod, nome, telefone) self.lstagenda.append(lista_pergunta)
def events(): """ retrieve the event data which was selected in the calendars using AJAX """ service = get_gcal_service(valid_credentials()) selected_cals = request.json['ids'] #print(selected_cals) #ret =[] begin_date = arrow.get(flask.session['begin_date']) end_date = arrow.get(flask.session['end_date']) if begin_date == end_date: differ = 1 else: differ = ((end_date - begin_date).days) + 1 begin_query = time_el(begin_date, flask.session['begin_time']) end_query = time_el(end_date, flask.session['end_time']) #interpret free times using agenda.py result =[] busy = [] free = Appt(arrow.get(begin_query), arrow.get(end_query)) for day in range(differ): for cal_id in selected_cals: av_agenda = Agenda() events = service.events().list(calendarId=cal_id, timeMin=begin_query, timeMax=end_query, singleEvents=True, orderBy="startTime").execute() for event in events['items']: strt = arrow.get(event['start']['dateTime']) end = arrow.get(event['end']['dateTime']) av_agenda.append(Appt(strt, end)) result.append({'summary': event['summary'], "startTime": arrow.get(event['start']['dateTime']).format("MM/DD/YYYY HH:mm"), "endTime": arrow.get(event['end']['dateTime']).format("MM/DD/YYYY HH:mm")}) busy.append(av_agenda) begin_query = next_day(begin_query) # should go one day after end_query = next_day(end_query)
def test_23_ligar_contato(self): a1 = Agenda('Rafael', '11999887766', '*****@*****.**') a1.novo_contato('Ana', '11999888563', '*****@*****.**') a1.novo_contato('Pedro', '1955552222', '*****@*****.**') a1.novo_contato('Mariana', '21145145145', '*****@*****.**') a1.novo_contato('João', '1152525252', '*****@*****.**') a1.contatos[2].adiciona_telefone('45124512', 'casa') ligar01 = a1.ligar('ana') ligar02 = a1.ligar('9888', 'casa') ligar03 = a1.ligar('52') ligar04 = a1.ligar('email.com', 'casa') resp = [ 'Ligando para Ana: <Telefone: 11999888563>', 'Nenhum contato possui o tipo de telefone dado!', 'Ligando para Pedro: <Telefone: 1955552222>', 'Ligando para Mariana: <Telefone: 45124512>' ] msg = 'Método ligar não retornou a mensagem correta' assert ligar01 == resp[0], msg assert ligar02 == resp[1], msg assert ligar03 == resp[2], msg assert ligar04 == resp[3], msg
def get_free_times(busytimes, dStart, dEnd, tStart, tEnd): freetimes = [] begin = arrow.get(dStart) end = arrow.get(dEnd) time_begin = combine_date_time(begin, arrow.get(tStart)) time_end = combine_date_time(begin, arrow.get(tEnd)) i = 0 for day in busytimes: busytimes_today = Agenda() for item in day: busytimes_today.append(Appt.from_iso_date(item['start'],item['end'],item['descr'])) timeframe = Appt.from_iso_date(time_begin,time_end,"Free Time") freetimes.append(busytimes_today.complement(timeframe)) #advance the day to sync with the next iteration time_begin = next_day(time_begin) time_end = next_day(time_end) return freetimes
def mergeBusyTimes(newTimes, oldTimes, dStart, dEnd): busytimes = [] begin = arrow.get(dStart) end = arrow.get(dEnd) i = 0 j = 0 for day in arrow.Arrow.range('day',begin,end): busytimes_today = Agenda() for appt in newTimes[i:]: if same_date(day.isoformat(), appt['start']): busytimes_today.append(Appt.from_iso_date(appt['start'],appt['end'],'Busy')) i=i+1 if(len(oldTimes) > j): for appt in oldTimes[j]: busytimes_today.append(Appt.from_iso_date(appt['start'],appt['end'],appt['descr'])) busytimes.append(busytimes_today) j=j+1 return busytimes