示例#1
0
def eliminar_contacto():
    """Activa la opcion de eliminar un contacto a traves de su indice."""

    while True:
        print("""
        {}ADVERTENCIA!!, no es posible recuperar contactos borrados.{}

        {}Para eliminar un contacto debes introducir su id, asegurate de
        saberlo antes de proceder.{}
        """.format(c.ROJO + c.BOLD, c.ENDC, c.VERDE + c.BOLD, c.ENDC))

        opcion = input(c.CYAN + "[DESEAS CONTINUAR?][SI/NO]: " + c.ENDC)

        if opcion.lower() == 'si':
            indice = input(c.VERDE + "[ID]: " + c.ENDC)

            Agenda.eliminar_registro(indice)

        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.")
示例#2
0
def busqueda_personalizada():
    """Realiza una busqueda por parametros dentro de la agenda."""

    while True:
        print(
            c.VERDE, c.BOLD, """
        En este submenu puedes realizar una busqueda por Nombre,
        Apellido o el numero de Telefono.

        NOTA: Mayusculas y minusculas cuentan.

        """, c.ENDC)

        opcion = input(c.CYAN + "[DESEAS CONTINUAR?][SI/NO]: " + c.ENDC)

        if opcion.lower() == 'si':
            filtro = input(c.VERDE + "Filtrar por campo [Nombre(default)]: " +
                           c.ENDC)

            busqueda = input(c.VERDE + "[A quien buscas?]: " + c.ENDC)

            Agenda.buscar_registro("Nombre", busqueda) if filtro == '' else \
                Agenda.buscar_registro(filtro, busqueda)

        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.")
示例#3
0
def ver_contactos():
    """Muestra un submenu que permite filtrar la forma en que
    se muestran los contactos, por Nombre, Apellido o Edad"""

    while True:
        print(
            c.VERDE, c.BOLD, """
        Antes de ver los contactos puedes filtrarlos por Nombre,
        Apellido o por Edad.

        """, c.ENDC)

        opcion = input(c.CYAN + "[DESEAS CONTINUAR?][SI/NO]: " + c.ENDC)

        if opcion.lower() == 'si':
            filtro = input(c.VERDE + "Filtro [Nombre(default)]: " + c.ENDC)

            if filtro.title() in ("Nombre", "Apellido", "Edad"):
                Agenda.listar_contactos(filtro.title())

            elif filtro == '':
                Agenda.listar_contactos("Nombre")

            else:
                c.error(
                    "Solo Nombre[default], Apellido o Edad son permitidos!")

        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.")
示例#4
0
 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()
示例#5
0
    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()
示例#6
0
 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')
示例#7
0
    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))
示例#8
0
文件: main.py 项目: lauMv/mvc-labo6
 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()
示例#9
0
class InterfaceAgenda():
    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 onDestroy(self, *args):
        Gtk.main_quit()

    def btnInserir(self, button):
        self.ag.nome = self.nomeCaixa.get_text()
        self.ag.telefone = self.telefoneCaixa.get_text()
        self.lb_status.set_text(str(self.ag.inserir()))
        self.nomeCaixa.set_text("")
        self.telefoneCaixa.set_text("")

    def btnAtualizar(self, button):
        self.ag.nome = self.nomeCaixa.get_text()
        self.ag.telefone = self.telefoneCaixa.get_text()
        self.lb_status.set_text(str(self.ag.atualizar()))
        self.nomeCaixa.set_text("")
        self.telefoneCaixa.set_text("")

    def btnApagar(self, button):
        self.ag.nome = self.nomeCaixa.get_text()
        self.ag.telefone = self.telefoneCaixa.get_text()
        self.lb_status.set_text(str(self.ag.apagar(self.ag.id)))
        self.nomeCaixa.set_text("")
        self.telefoneCaixa.set_text("")

    def btnBuscar(self, button):
        self.ag.nome = self.nomeCaixa.get_text()
        self.lb_status.set_text(str(self.ag.buscar(self.ag.nome)))
        self.telefoneCaixa.set_text(self.ag.telefone)
示例#10
0
 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
示例#11
0
    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()
示例#12
0
def find_free(events):
    """
    uses the not free events to find the free blocks
    :param events: dict of busy events
    :return: dict of free times
    """
    #pass in the event list
    agenda = Agenda.from_dict(events)
    app.logger.debug("Find Free Events")

    #Just get all the block in questions info
    start_date = arrow.get(flask.session['begin_date']).date()
    end_date = arrow.get(flask.session['end_date']).date()
    start_time = arrow.get(flask.session['start_time']).time()
    end_time = arrow.get(flask.session['end_time']).time()

    #Make two arrow objects for freeblock query
    begin = arrow.Arrow(start_date.year, start_date.month, start_date.day, start_time.hour, start_time.minute)
    end = arrow.Arrow(end_date.year, end_date.month, end_date.day, end_time.hour, end_time.minute)

    free = Appt(begin, end, "Free")
    free_time = agenda.complement(free)
    app.logger.debug(free_time.list_convert())

    #convert to dict for later use
    return free_time.list_convert()
 def __init__(self, wcfg, wfsa, slice_vars):
     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()
     self.slice_vars = slice_vars
示例#14
0
文件: main.py 项目: lauMv/mvc-labo6
class Main:
    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 agregar(self, nombre, telefono):
        self.contacto[nombre] = Contacto(nombre, telefono)

    def borrar(self, nombre):
        del self.contacto[nombre]

    def mostrar(self, nombre):
        return self.contacto[nombre]

    def listar(self):
        return (self.contacto[nombre] for nombre in sorted(self.contacto))

    def salir(self):
        salir()
示例#15
0
    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
示例#16
0
 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)
示例#17
0
    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
示例#18
0
    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 __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()
示例#20
0
文件: main.py 项目: DZZ95/invoker
 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()
示例#21
0
 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
示例#22
0
def modificar_contacto():
    """Activa la opcion de modificar un contacto en la agenda."""

    while True:
        print("""
        {}Aqui puedes modificar un contacto atraves de su indice(id)
        asegurate de saber el indice correcto antes de modificar.{}

        {}NOTA: Los cambios no son reversibles.{}
        """.format(c.VERDE + c.BOLD, c.ENDC, c.ROJO + c.BOLD, c.ENDC))

        opcion = input(c.CYAN + "[DESEAS CONTINUAR?][SI/NO]: " + c.ENDC)

        if opcion.lower() == 'si':
            indice = input(c.VERDE + "[ID]: " + c.ENDC)
            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)

            if indice != '' and nombre != '' and apellido != '' and \
                    edad != '' and telefono != '' and email != '':

                modificado = Contacto(nombre, apellido, edad, telefono, email)
                if modificado.es_valido():
                    Agenda.modificar_registro(indice,
                                              *modificado.obtener_datos())
                    c.success(
                        "El contacto con el ID {} se ha modificado!".format(
                            indice))

                else:
                    c.error("Verifica los datos, algo anda mal.")
            else:
                c.error("Faltan datos, el contacto no se ha modificado!!")

        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_shift(self):
     agenda = Agenda()
     shift = agenda.add_shift(9, 14)
     self.assertEqual(Interval(9, 14), agenda.get_shift(shift))
     shifts = list(agenda.get_shifts_iter())
     self.assertEqual(shifts, [(shift, Interval(9, 14)), ])
     agenda.del_shift(shift)
     shifts = list(agenda.get_shifts_iter())
     self.assertEqual(shifts, [])
示例#24
0
    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)
示例#25
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')
示例#26
0
 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'
示例#27
0
 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()
示例#28
0
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)
示例#29
0
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}
示例#30
0
 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())
示例#31
0
	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))
示例#32
0
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
示例#33
0
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.")
示例#34
0
 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
示例#35
0
 def valida_registro(self):
     if (self.tabela == 4) or (self.tabela == 5):
         r = Agenda.pesquida_agenda(self.pk1)
         if not (r) and (self.acao != 3):
             self.baixa_controle()
             return False
         elif (len(r) > 0) and (r[0]['DATA'] < date.today()):
             self.baixa_controle()
             return False
         else:
             return True
     elif (self.tabela == 3):
         self.baixa_controle()
     else:
         return True
class SlicedEarley(object):
    """
    """

    def __init__(self, wcfg, wfsa, slice_vars):
        """
        """

        self._wcfg = wcfg
        self._wfsa = wfsa
        self._agenda = Agenda(active_container_type=ActiveQueue)
        self._predictions = set()  # (LHS, start)
        self._item_factory = ItemFactory()
        self.slice_vars = slice_vars

    def get_item(self, rule, dot, inner=[]):
        return self._item_factory.get_item(rule, dot, inner)

    def advance(self, item, dot):
        """returns a new item whose dot has been advanced"""
        return self.get_item(item.rule, dot, item.inner + (item.dot,))

    def axioms(self, symbol, start):
        rules = self._wcfg.get(symbol, None)
        if rules is None:  # impossible to rewrite the symbol
            return False
        if (symbol, start) in self._predictions:  # already predicted
            return True
        # otherwise add rewritings to the agenda
        self._predictions.add((symbol, start))
        self._agenda.extend(self.get_item(rule, start) for rule in rules)
        return True

    def prediction(self, item):
        """
        This operation tris to create items from the rules associated with the nonterminal ahead of the dot.
        It returns True when prediction happens, and False if it already happened before.
        """
        if (item.next, item.dot) in self._predictions:  # prediction already happened
            return False
        self._predictions.add((item.next, item.dot))
        new_items = [self.get_item(rule, item.dot) for rule in self._wcfg.get(item.next, frozenset())]
        self._agenda.extend(new_items)
        return True

    def scan(self, item):
        """
        This operation tries to scan over as many terminals as possible,
        but we only go as far as determinism allows.
        If we get to a nondeterminism, we stop scanning and add the relevant items to the agenda.
        """
        states = [item.dot]
        for sym in item.nextsymbols():
            if is_terminal(sym):
                arcs = self._wfsa.get_arcs(origin=states[-1], symbol=sym)
                if len(arcs) == 0:  # cannot scan the symbol
                    return False
                elif len(arcs) == 1:  # symbol is scanned deterministically
                    sto, _ = arcs[0]
                    states.append(sto)  # we do not create intermediate items, instead we scan as much as we can
                else:  # here we found a nondeterminism, we create all relevant items and add them to the agenda
                    # create items
                    for sto, w in arcs:
                        self._agenda.add(self.get_item(item.rule, sto, item.inner + tuple(states)))
                    return True
            else:  # that's it, scan bumped into a nonterminal symbol, time to wrap up
                break
        # here we should have scanned at least one terminal symbol
        # and we defined a deterministic path
        self._agenda.add(self.get_item(item.rule, states[-1], item.inner + tuple(states[:-1])))
        return True

    def complete_others(self, item):
        """
        This operation creates new item by advancing the dot of passive items that are waiting for a certain given complete item.
        It returns whether or not at least one passive item awaited for the given complete item.
        """
        if self._agenda.is_generating(item.rule.lhs, item.start, item.dot):
            return True
        new_items = [self.advance(incomplete, item.dot) for incomplete in self._agenda.iterwaiting(item.rule.lhs, item.start)]
        self._agenda.extend(new_items)
        return len(new_items) > 0  # was there any item waiting for the complete one?


    def complete_itself(self, item):
        """
        This operation tries to merge a given incomplete item with a previosly completed one.
        """
        new_items = [self.advance(item, sto) for sto in self._agenda.itercompletions(item.next, item.dot)]
        self._agenda.extend(new_items)
        return len(new_items) > 0

    def do(self, root='[S]', goal='[GOAL]'):

        wfsa = self._wfsa
        wcfg = self._wcfg
        agenda = self._agenda

        # start items of the kind
        # GOAL -> * ROOT, where * is an intial state of the wfsa
        if not any(self.axioms(root, start) for start in wfsa.iterinitial()):
            raise ValueError('No rule for the start symbol %s' % root)
        new_roots = set()

        while agenda:
            item = agenda.pop()  # always returns an active item

            if item.is_complete():
                # get slice variable for the current completed item
                u = self.slice_vars.get(item.rule.lhs, item.start, item.dot)

                # check whether the probability of the current completed item is above the threshold determined by
                # the slice variable
                if item.rule.log_prob > u:
                    # complete root item spanning from a start wfsa state to a final wfsa state
                    if item.rule.lhs == root and wfsa.is_initial(item.start) and wfsa.is_final(item.dot):
                        agenda.make_complete(item)
                        new_roots.add((root, item.start, item.dot))
                        agenda.make_passive(item)
                    else:
                        if self.complete_others(item):
                            agenda.make_complete(item)
                            agenda.make_passive(item)
                        else:  # a complete state is only kept in case it could potentially complete others
                            agenda.discard(item)
            else:
                if is_terminal(item.next):
                    # fire the operation 'scan'
                    self.scan(item)
                    agenda.discard(item)  # scanning renders incomplete items of this kind useless
                else:
                    if not wcfg.can_rewrite(item.next):  # if the NT does not exist this item is useless
                        agenda.discard(item)
                    else:
                        if not self.prediction(item):  # try to predict, otherwise try to complete itself
                            self.complete_itself(item)
                        agenda.make_passive(item)
        # converts complete items into rules
        logging.debug('Making forest...')
        return self.get_cfg(goal, root)

    def get_intersected_rule(self, item):
        lhs = make_symbol(item.rule.lhs, item.start, item.dot)
        positions = item.inner + (item.dot,)
        rhs = [make_symbol(sym, positions[i], positions[i + 1]) for i, sym in enumerate(item.rule.rhs)]
        return Rule(lhs, rhs, item.rule.log_prob)

    def get_cfg(self, goal, root):
        """
        Constructs the CFG by visiting complete items in a top-down fashion.
        This is effectively a reachability test and it serves the purpose of filtering nonterminal symbols
        that could never be reached from the root.
        Note that bottom-up intersection typically does enumerate a lot of useless (unreachable) items.
        This is the recursive procedure described in the paper (Nederhof and Satta, 2008).
        """

        G = WCFG()
        processed = set()
        fsa = self._wfsa
        itergenerating = self._agenda.itergenerating
        itercomplete = self._agenda.itercomplete

        def make_rules(lhs, start, end):
            if (start, lhs, end) in processed:
                return
            processed.add((lhs, start, end))
            for item in itercomplete(lhs, start, end):
                G.add(self.get_intersected_rule(item))
                fsa_states = item.inner + (item.dot,)
                for i, sym in itertools.ifilter(lambda (_, s): is_nonterminal(s), enumerate(item.rule.rhs)):
                    if (sym, fsa_states[i], fsa_states[
                            i + 1]) not in processed:  # Nederhof does not perform this test, but in python it turned out crucial
                        make_rules(sym, fsa_states[i], fsa_states[i + 1])

        # create goal items
        for start, ends in itergenerating(root):
            if not fsa.is_initial(start):
                continue
            for end in itertools.ifilter(lambda q: fsa.is_final(q), ends):
                make_rules(root, start, end)
                G.add(Rule(make_symbol(goal, None, None),
                           [make_symbol(root, start, end)], 0.0))

        return G
示例#37
0
 def run(self):
     agenda = Agenda(self.c)
     agenda.schedule(0, self.arrival, [])
     agenda.schedule(0, self.monitor, [])
     while agenda.has_events():
         agenda.next_event()
    def test_appointment(self):
        agenda = Agenda()
        shift = agenda.add_shift(9, 14)

        app1 = agenda.add_appointment(9, 10)
        self.assertEqual(Interval(9, 10), agenda.get_appointment(app1))

        agenda.del_appointment(app1)

        app2 = agenda.add_appointment(9, 10)
        self.assertEqual(Interval(9, 10), agenda.get_appointment(app2))

        with self.assertRaises(NotAvailableSlotError):
            agenda.add_appointment(9, 11)

        with self.assertRaises(ShiftNotEmptyError):
            agenda.del_shift(shift)
示例#39
0
  Each agenda file is a list of appointments.
"""

from agenda import Appt, Agenda
import sys
import argparse

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Find a time we can all meet.")
    parser.add_argument('date', help="Date to check for available times, format like 2012.05.31")
    parser.add_argument('earliest', help="Earliest potential time to start, format like 8:30")
    parser.add_argument('latest', help="Latest potential time to end, format like 18:00")
    parser.add_argument('participant', help="A text file containing an agenda, e.g., 'charles.ag'", 
                         nargs="*", type=argparse.FileType('r'))

    available = Agenda()
    args = parser.parse_args()
    blockspec = args.date + " " + args.earliest + " " + args.latest + "|Available"
    freeblock = Appt.from_string(blockspec)
    available.append(freeblock)

    appointments = Agenda()   # Create empty agenda

    for f in args.participant:  
        participant = Agenda.from_file(f)
        for appt in participant:   # Cycle through every appointment 
            appointments.append(appt)   
    available = appointments.complement(freeblock)

    if len(available) == 0:
        print("No free times in common")
示例#40
0
       is returned through the commandwindow notifying the "No free times in common"
"""

from agenda import Appt, Agenda
import sys
import argparse

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Find a time we can all meet.")
    parser.add_argument('date', help="Date to check for available times, format like 2012.05.31")
    parser.add_argument('earliest', help="Earliest potential time to start, format like 8:30")
    parser.add_argument('latest', help="Latest potential time to end, format like 18:00")
    parser.add_argument('participant', help="A text file containing an agenda, e.g., 'charles.ag'", 
                         nargs="*", type=argparse.FileType('r'))

    available = Agenda()
    args = parser.parse_args()
    blockspec = args.date + " " + args.earliest + " " + args.latest + "|Available"
    freeblock = Appt.from_string(blockspec)
    available.append(freeblock)

    for f in args.participant: 
        participant = Agenda.from_file(f)
        available = available.intersect(participant)

    if len(available) == 0:
        print("No free times in common")

    else:
        print(available)
    
class SlicedNederhof(object):
    """
    This is an implementation of the CKY-inspired intersection due to Nederhof and Satta (2008).
    """

    def __init__(self, wcfg, wfsa, slice_vars):
        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()
        self.slice_vars = slice_vars

    def get_item(self, rule, dot, inner=[]):
        return self._item_factory.get_item(rule, dot, inner)
    
    def advance(self, item, dot):
        """returns a new item whose dot has been advanced"""
        return self.get_item(item.rule, dot, item.inner + (item.dot,))
        
    def add_symbol(self, sym, sfrom, sto):
        """
        This operation:
            1) completes items waiting for `sym` from `sfrom`
            2) instantiate delayed axioms
        Returns False if the annotated symbol had already been added, True otherwise
        """
        
        if self._agenda.is_generating(sym, sfrom, sto):
            return False

        # every item waiting for `sym` from `sfrom`
        for item in self._agenda.iterwaiting(sym, sfrom):
            self._agenda.add(self.advance(item, sto))

        # you may interpret this as a delayed axiom
        # every compatible rule in the grammar
        for r in self._firstsym.get(sym, set()):  
            self._agenda.add(self.get_item(r, sto, inner=(sfrom,)))  # can be interpreted as a lazy axiom

        return True

    def axioms(self):
        """
        The axioms of the program are based on the FSA transitions. 
        """
        # you may interpret the following as a sort of lazy axiom (based on grammar rules)
        for r in self._wcfg:
            self._firstsym[r.rhs[0]].add(r)
        # these are axioms based on the transitions of the automaton
        for sfrom, sto, sym, w in self._wfsa.iterarcs():
            self.add_symbol(sym, sfrom, sto)  

    def inference(self):
        """Exhausts the queue of active items"""
        agenda = self._agenda
        while agenda:
            item = agenda.pop()  # always returns an ACTIVE item
            # complete other items (by calling add_symbol), in case the input item is complete
            if item.is_complete():
                u = self.slice_vars.get(item.rule.lhs, item.start, item.dot)
                # check whether the probability of the current completed item is above the threshold determined by
                # the slice variable
                if item.rule.log_prob > u:
                    self.add_symbol(item.rule.lhs, item.start, item.dot)  # prove the symbol
                    agenda.make_complete(item)  # mark the item as complete
            else:
                # merges the input item with previously completed items effectively moving the input item's dot forward
                agenda.make_passive(item)
                for sto in agenda.itercompletions(item.next, item.dot):
                    agenda.add(self.advance(item, sto))  # move the dot forward

    def do(self, root='[S]', goal='[GOAL]'):
        """Runs the program and returns the intersected CFG"""
        self.axioms()
        self.inference()
        return get_cfg(goal, root, self._wfsa, self._agenda)
示例#42
0
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())
    
    
示例#43
0
	def teste_colisao_agendas_vazias(self):
		agenda1 = Agenda()
		agenda2 = Agenda()
		
		self.assertFalse(agenda1.colide(agenda2))