示例#1
0
    def __init__ (self, folder, olprops=None, eid=None, con=None):
        """Constructor for OLContact. The starting properties of the contact
        can be initialized either from an existing Contact object, or from an
        Outlook item property list. It is an error to provide both.

        It is redundant to provide both olprops (array of property tuples) and
        an entryid. The entryid will override the property list.
        """

        if ((olprops and con) or (eid and con)):
            raise OLContactError(
                'Both olprops/eid and con cannot be specified in OLContact()')

        if olprops and eid:
            logging.warning('olprops and eid are not null. Ignoring olprops')
            olprops = None

        Contact.__init__(self, folder, con)

        ## Sometimes we might be creating a contact object from GC or other
        ## entry which might have the Entry ID in its sync tags
        ## field. if that is present, we should use it to initialize the
        ## itemid field for the current object

        conf = self.get_config()
        if con:
            try:
                pname_re = conf.get_profile_name_re()
                label    = conf.make_sync_label(pname_re, self.get_dbid())
                tag, itemid = con.get_sync_tags(label)[0]              
                self.set_entryid(base64.b64decode(itemid))
            except Exception, e:
                logging.debug('Potential new OLContact: %s', con.get_name())
示例#2
0
    def __init__ (self, folder, con=None, vco=None, itemid=None):
        """vco, if not None, should be a valid vCard object (i.e. the contents
        of a vCard file, for e.g. When vco is not None, itemid should also be
        not None"""

        Contact.__init__(self, folder, con)

        self.set_etag(None)
        self.set_uid(None)
        self.set_vco(vco)
        self._group_count = 0

        ## Sometimes we might be creating a contact object from a Google
        ## contact object or other entry which might have the ID in its sync
        ## tags field. if that is present, we should use it to initialize the
        ## itemid field for the current object

        conf = self.get_config()
        if con:
            try:
                pname_re = conf.get_profile_name_re()
                label    = conf.make_sync_label(pname_re, self.get_dbid())
                tag, itemid = con.get_sync_tags(label)[0]              
                self.set_itemid(itemid)
            except Exception, e:
                logging.debug('Potential new CDContact: %s', con.get_name())
示例#3
0
    def __init__ (self, folder, con=None, con_itemid=None, rec=None):
        """rec is the native string vector representation of a BBDB contact
        entry on disk."""

        Contact.__init__(self, folder, con)
        self.atts.update({'bbdb_folder' : None,})

        conf = self.get_config()
        if con:
            if con_itemid:
                self.set_itemid(con_itemid)
            else:
                logging.debug('Potential new BBContact: %s', con.get_name())

        if folder.get_name():
            self.set_bbdb_folder(folder.get_name())

        if rec:
            self.set_rec(rec)
            self.init_props_from_rec(rec)

        if not self.get_itemid():
            iid = ('%s' % uuid.uuid1())
            logging.debug('Assigning UUID %s for new contact: %s', iid, 
                          self.get_name())
            self.set_itemid(iid)

        self.in_init(False)
示例#4
0
    def __init__ (self, folder, con=None, rec=None):
        """rec is the native string vector representation of a BBDB contact
        entry on disk."""

        Contact.__init__(self, folder, con)

        self.atts.update({'bbdb_folder' : None,})

        ## Sometimes we might be creating a contact object from a Google
        ## contact object or other entry which might have the ID in its sync
        ## tags field. if that is present, we should use it to initialize the
        ## itemid field for the current object

        conf = self.get_config()
        if con:
            try:
                pname_re = conf.get_profile_name_re()
                label    = conf.make_sync_label(pname_re, self.get_dbid())
                tag, itemid = con.get_sync_tags(label)[0]              
                self.set_itemid(itemid)
            except Exception, e:
                logging.debug('Potential new BBContact: %s', con.get_name())

            if folder.get_name():
                self.set_bbdb_folder(folder.get_name())
示例#5
0
    def __init__ (self, folder, con=None, con_itemid=None, vco=None, itemid=None,
                  debug_vcf=False):
        """vco, if not None, should be a valid vCard object (i.e. the contents
        of a vCard file, for e.g. When vco is not None, itemid should also be
        not None"""

        Contact.__init__(self, folder, con)

        self.debug_vcf = debug_vcf

        self.set_etag(None)
        self.set_uid(None)
        self.set_vco(vco)
        self._group_count = 0

        conf = self.get_config()
        if con:
            if con_itemid:
                self.set_itemid(self.normalize_cdid(con_itemid))
            else:
                logging.debug('Potential new CDContact: %s', con.get_name())
        elif vco:
            self.init_props_from_vco(vco)
            if not self.debug_vcf:
                assert(itemid)
            self.set_itemid(itemid)

        self.in_init(False)

        if not self.get_uid():
            self.set_uid(str(uuid.uuid1()))
示例#6
0
    def __init__ (self, folder, ews_con=None, con=None):
        """Constructor for EXContact. The starting properties of the contact
        can be initialized either from an existing Contact object, or from an
        pyews contact object. It is an error to provide both.
        """

        if (ews_con and con):
            raise EXContactError(
                'Both ews con and con cannot be specified in EXContact()')

        Contact.__init__(self, folder, con)

        ## Sometimes we might be creating a contact object from a remote
        ## source which might have the Entry ID in its sync tags field. if
        ## that is present, we should use it to initialize the itemid field
        ## for the current object

        conf = self.get_config()
        if con:
            try:
                pname_re = conf.get_profile_name_re()
                label    = conf.make_sync_label(pname_re, self.get_dbid())
                tag, itemid = con.get_sync_tags(label)[0]              
                self.set_itemid(itemid)
            except Exception, e:
                logging.debug('Potential new EXContact: %s', con.get_disp_name())
示例#7
0
 def extract_contact(self):
     if not self.type_in(c.IPMSG_BR_ENTRY, c.IPMSG_ANSENTRY):
         contact = Contact(name=self.name, group='', host=self.host, addr=self.addr, login=self.name)
         contact.temporary = True
     else:
         contact = Contact(name=self.msg, group=self.group, host=self.host, addr=self.addr, login=self.name)
         contact.encrypt_opt = self.test(c.IPMSG_ENCRYPTOPT)
     return contact
示例#8
0
def main():
    bd = GestionBD(BaseMySQL.dbName, BaseMySQL.user,
                    BaseMySQL.passwd, BaseMySQL.host)
    if bd.echec:
        sys.exit()
    while 1:
        print "\nQue voulez-vous faire :\n"\
          "1) Créer les tables de la base de données\n"\
          "2) Supprimer les tables de la base de données ?\n"\
          "3) Entrer des employés\n"\
          "4) Lister des employés\n"\
          "5) Exécuter une requête SQL quelconque\n"\
          "6) Enregister sous format ldif\n"\
          "7) Terminer ?                         Votre choix :",
        ch = int(raw_input())
        if ch == 1:
            # Create all the tables described in the thesaurus
            bd.creerTables(BaseMySQL.dicoT)
        elif ch == 2:
            # Drop all the tables described in the thesaurus
            bd.supprimerTables(BaseMySQL.dicoT)
        elif ch == 3:
            # Integration of employees
            table = {3: 'employes'}[ch]
            enreg = Sauvegarde(bd, table)
            while 1:
                if enreg.save():
                    break
        elif ch == 4:
            # List of all employees
            table = {4: 'employes'}[ch]
            if bd.executerReq("SELECT * FROM %s" % table):
                records = bd.resultatReq()
                for rec in records:
                    for item in rec:
                        print item,
                    print
        elif ch == 5:
            # Any query
            req = raw_input("Enter SQL query : ")
            if bd.executerReq(req):
                print bd.resultatReq()
        elif ch == 6:
            # Save
            fic = raw_input('Enter filename to process: ')
            ofi = open(fic, "w")
            contact = Contact()
            table = {6: 'employes'}[ch]
            if bd.executerReq("SELECT * FROM %s" % table):
                records = bd.resultatReq()
                for rec in records:
                    contact = Contact(*rec[1:])
                    ofi.write(contact.get_contact_ldif())
                ofi.close()
        else:
            bd.commit()
            bd.close()
            break
示例#9
0
 def testDeleteContactById(self):
     contactId = 1
     #check if contact #1 exist
     contact = Contact.retrieve(contactId)
     self.failUnless(contact)
     
     #delete contact #1 
     successful = contact.delete()
     self.failUnless(successful)
     
     #confirm contact #1 no longer exist
     contact = Contact.retrieve(contactId)
     self.failIf( contact )
示例#10
0
    def __init__(self, prompt=":> ", quitChar='\\'):
        self.prompt = prompt
        self.quitChar = quitChar
        self.mainMenu = """   
        {}   Exit Prompt
        1   Create Contact
        2   Edit Contact
        3   Delete Contact
        4   Show Contact 
@Main{}""".format(quitChar, prompt )
        contactDb = ContactsDb('localhost', 'root', '1234', 'contacts_orm', 'contacts' )
        Contact.connect(contactDb)
        pass
示例#11
0
 def new_contact(self, token, name, surname):
     """
     Create new contact
     :param token: which returned by user login
     :param name: Name of the new contact
     :param surname: Surname of the new Contact
     :return:
     """
     user = User.get_by_id(token.userid)
     if not user:
         return errors.UserDoesNotFound()
     Contact.new_contact(user._id, name, surname)
     return {}
示例#12
0
 def showContactPrompt(self):
     shower = ShowContactPrompt(self.prompt)
     id = shower.readContactIdToShow()
     if id == -1:
         contacts = Contact.retrieveAll()
         shower.showAll(contacts)
         return 
     
     contact = Contact.retrieve(id)
     if contact:
         shower.show(contact)
     else:
         print 'Contact #{} does not exist'.format(id)
         shower.readContactIdToShow()
示例#13
0
文件: contact_gc.py 项目: xgid/ASynK
    def __init__(self, folder, con=None, con_itemid=None, gce=None):
        Contact.__init__(self, folder, con)

        conf = self.get_config()
        if con:
            if con_itemid:
                self.set_itemid(self.normalize_gcid(con_itemid))
            else:
                logging.debug("Potential new GCContact: %s", con.get_disp_name())

        self.set_gce(gce)
        if gce:
            self.init_props_from_gce(gce)

        self.in_init(False)
示例#14
0
 def got_forward_message(self, contact, obj):
   self.forward(
     key=obj.key,
     message=obj.message,
     raw_key=obj.raw_key,
     requester=Contact.from_tuple(obj.requester, self)
     )
示例#15
0
    def __initialization(self, data):
        if data is None:
            raise Exception("Data is invalid")

        self.firstname = data.get('firstname', None)
        self.lastname = data.get(u'lastname', None)
        self.birthdate = data.get('birthdate', None)
        birthplace = data.get('birthplace', None)
        if birthplace is not None:
            self.birthplace = Place(birthplace)

        employers = data.get('work_experience', [])
        if isinstance(employers, list):
            for employer in employers:
                self.work_experience.append(
                    Employer(employer)
                )

        degrees = data.get('education', [])
        if isinstance(degrees, list):
            for degree in degrees:
                self.education.append(Degree(degree))

        contacts = data.get('contacts', [])
        if isinstance(contacts, list):
            for contact in contacts:
                self.contacts.append(Contact.get_instance(contact))
示例#16
0
 def testEditContactName(self):
     contactId = 1
     oldName, newName = 'Lennox', 'Leonard'
     #check confirm contact's old name
     contact = Contact.retrieve(contactId)
     self.assertEquals(contact.name, oldName)
     self.assertNotEquals(contact.name, newName)
     
     #update contact's name
     contact.name = newName
     successful = contact.update()
     self.failUnless(successful)
     
     #confirm contact's new name after update
     contact = Contact.retrieve(contactId)
     self.assertEquals(contact.name, newName)
     self.assertNotEquals(contact.name, oldName)
示例#17
0
 def testEditContactPhone(self):
     contactId = 1
     oldPhone, newPhone = '02099888999', '02011222111'
     #check confirm contact's old phone
     contact = Contact.retrieve(contactId)
     self.assertEquals(contact.phone, oldPhone)
     self.assertNotEquals(contact.phone, newPhone)
     
     #update contact's phone
     contact.phone = newPhone
     successful = contact.update()
     self.failUnless(successful)
     
     #confirm contact's new name after update
     contact = Contact.retrieve(contactId)
     self.assertEquals(contact.phone, newPhone)
     self.assertNotEquals(contact.phone, oldPhone)
示例#18
0
	def test_get_all_list_of_contacts(self):
		contact1 = Contact("p1",123,"[email protected]")
		contact2 = Contact("p2",123,"[email protected]")
		contact1.save()
		contact2.save()
		contacts = Contact.all()
		self.assertEqual(len(contacts), 2)
示例#19
0
文件: contact_gc.py 项目: barak/ASynK
    def __init__(self, folder, con=None, gce=None):
        Contact.__init__(self, folder, con)

        ## Sometimes we might be creating a contact object from Outlook or
        ## other entry which might have the google contact ID in its sync tags
        ## field. if that is present, we should use it to initialize the
        ## itemid field for the current object

        conf = self.get_config()
        if con:
            try:
                pname_re = conf.get_profile_name_re()
                label = conf.make_sync_label(pname_re, self.get_dbid())
                tag, itemid = con.get_sync_tags(label)[0]

                self.set_itemid(self.normalize_gcid(itemid))
            except Exception, e:
                logging.debug("Potential new GCContact: %s", con.get_name())
示例#20
0
 def deleteContactPrompt(self):
     deleter = DeleteContactPrompt(self.prompt)
     id = deleter.readContactIdForDeletion()
     contact = Contact.retrieve(id)
     if contact:
         if contact.delete() :
             print '{} DELETED'.format(contact) 
     else:
         print 'Contact #{} does not exist'.format(id)
         self.deleteContactPrompt()
示例#21
0
 def extract_contact_list(self):
     rslt = []
     if not self.type_in(c.IPMSG_ANSLIST):
         return []
     g_cnt, c_cnt, bunch = re.split('\x07', self.raw_msg, 2)
     raw_list = re.split('\x07', bunch)[:-1]
     while raw_list:
         raw = raw_list[:7]
         raw_list = raw_list[7:]
         tag = raw[2]
         addr = list(self.addr)
         addr[0] = raw[3]
         wtf = raw[4]
         name = self.to_unicode(raw[5])
         login = self.to_unicode(raw[0])
         group = self.to_unicode(raw[6])
         contact = Contact(name=name, group=group, host=raw[1], addr=tuple(addr), login=login)
         contact.encrypt_opt = (int(tag) & c.IPMSG_ENCRYPTOPT)
         rslt.append(contact)
     return rslt
示例#22
0
    def __init__ (self, folder, ews_con=None, con=None, con_itemid=None):
        """Constructor for EXContact. The starting properties of the contact
        can be initialized either from an existing Contact object, or from an
        pyews contact object. It is an error to provide both.
        """

        if (ews_con and con):
            raise EXContactError(
                'Both ews con and con cannot be specified in EXContact()')

        Contact.__init__(self, folder, con)

        conf = self.get_config()
        if con:
            if con_itemid:
                self.set_itemid(con_itemid)
            else:
                logging.debug('Potential new EXContact: %s', con.get_disp_name())

        self.set_ews_con(ews_con)
        if ews_con is not None:
            self.init_props_from_ews_con(ews_con)
示例#23
0
  def got_leave_message(self, contact, obj):
    # special case: only one node in the system
    if contact == self.contacts.me():
      # don't bother doing anything, just call the callback
      self.callback_manager.call(obj.request_id, contact)
      return

    for key in obj.data:
      self.data[key] = self.value_from_wire(obj.data[key])
    self.contacts.set_successor(Contact.from_tuple(obj.successor, self))
    self.contacts.get_successor().send(LeaveUpdateSuccessor(leaving=contact.to_tuple()))
    self.contacts.remove(contact)
    contact.send(LeaveResponse(request_id=obj.request_id))
示例#24
0
def randomContact():
        contact = Contact()
        contact.fname=randomString(10)
        contact.mname=randomString(10)
        contact.lname=randomString(10)
        contact.phone=randomString(10)
        contact.bday=str(random.randint(1,29))+"/"+str(random.randint(1,12))+"/"+str(1950+random.randint(0,60))
        return contact
示例#25
0
 def editContactPrompt(self):
     editor = EditContactPrompt(self.prompt)
     id = editor.readContactId()
     contact = Contact.retrieve(id)
     if contact:
         contact.name = editor.readEdittedName(contact.name)
         contact.phone = editor.readEdittedPhone(contact.phone)
         contact.gender = editor.readEdittedGender(contact.gender)
         contact.description = editor.readEdittedDescription(contact.description)
         contact.update()
         print '{} UPDATED\n'.format(contact)
     else:
         print 'Contact #{} does not exist'.format(id)
         self.editContactPrompt()
 def getContact(self):
     """get contacts from fields in gui"""
     contact = Contact()
     try:
         contact.cid   = self.cidEdit.text()
         contact.fname = self.fnameEdit.text()
         contact.mname = self.mnameEdit.text()
         contact.lname = self.lnameEdit.text()
         contact.phone = self.phoneEdit.text()
         contact.bday  = self.bdayEdit.text()
     except Exception as e:
         QMessageBox.question(self, 'Error', str(e), QMessageBox.Ok, QMessageBox.Ok)
     return contact
示例#27
0
    def __init__ (self, folder, con=None, vco=None, itemid=None):
        """vco, if not None, should be a valid vCard object (i.e. the contents
        of a vCard file, for e.g. When vco is not None, itemid should also be
        not None"""

        Contact.__init__(self, folder, con)

        self.set_etag(None)
        self.set_uid(None)
        self.set_vco(vco)
        self._group_count = 0

        ## Sometimes we might be creating a contact object from a Google
        ## contact object or other entry which might have the ID in its sync
        ## tags field. if that is present, we should use it to initialize the
        ## itemid field for the current object

        conf = self.get_config()
        if con:
            try:
                ## FIXME: The code below works for other DBs quite
                ## well. However with CardDAV there is a problem when the same
                ## item is synched to more than one server. This happens
                ## because the itemid is picked up from the first sync tag,
                ## and the itemid is also assumed to be the full path of the
                ## file on the server. For now we will assume that you will
                ## sync your contacts to a single carddav server... The proper
                ## solution is to pick out the sync tag corresponding to the
                ## profile being synched... That is itself a problem because
                ## this class is not as 'state-less' as it can/should be. WTF.
                pname_re = conf.get_profile_name_re()
                label    = conf.make_sync_label(pname_re, self.get_dbid())
                tag, itemid = con.get_sync_tags(label)[0]              
                self.set_itemid(itemid)
            except Exception, e:
                logging.debug('Potential new CDContact: %s', con.get_name())
示例#28
0
def main():
    user_name = input(
        "Hello, welcome to your contact list. What is your name? ")

    print(f"Hello {user_name}. What would you like to do?")
    print('\n')

    while True:
        print(
            "Use these short codes: \n cc - create a new contact \n dc - display contacts \n fc - find a contact \n ex - exit the contact list app \n del - delete a contact \n cpc - copy a contact email"
        )

        short_code = input().lower()

        if short_code == 'cc':
            print('New Contact')
            print('-' * 10)

            f_name = input('First name...:')

            l_name = input('Last name...:')

            p_number = input('Phone number...:')

            e_address = input('Email address...: ')

            save_contact(
                create_contact(f_name, l_name, p_number,
                               e_address))  #create and save new contact
            print('\n')
            print(f'New contact {f_name} {l_name} created')
            print('\n')

        elif short_code == 'dc':

            if display_contacts():
                print('Here is a list of all your contacts')
                print('\n')

                for contact in display_contacts():
                    print(
                        f'{contact.first_name} {contact.last_name} ......{contact.number}'
                    )

                print('\n')
            else:
                print('\n')
                print('You don\'t seem to have any contact saved yet')
                print('\n')

        elif short_code == 'fc':

            search_number = input('Enter the number you want to search for: ')

            if check_existing_contacts(search_number):
                search_contact = find_contact(search_number)
                print(
                    f'{search_contact.first_name} {search_contact.last_name}')
                print('-' * 20)

                print(
                    f'Phone number......: {search_contact.phone_number} \n Email address......: {search_contact.email}'
                )

            else:
                print('That contact does not exist')

        elif short_code == 'del':

            search_number = input('Enter the number you want to delete: ')

            if check_existing_contacts(search_number):
                search_contact = find_contact(search_number)
                print(
                    f'{search_contact.first_name} {search_contact.last_name}')
                print('-' * 20)

                del_contact(search_contact)
                print('Your contact has been deleted')

            else:
                print('That contact does not exist')

        elif short_code == 'cpc':

            search_number = input('Enter the number you want to copy: ')

            if check_existing_contacts(search_number):
                search_contact = find_contact(search_number)
                print(
                    f'{search_contact.first_name} {search_contact.last_name}')
                print('-' * 20)

                Contact.copy_email(search_number)
                print('\n Your contact has been copied. \n')

        elif short_code == 'ex':
            print('Bye..... It was fun while it lasted.... :-)')
            break

        else:
            print('I really didn\'t get that. Please use the short codes')
示例#29
0
    def store(self, key, value, originalPublisherID=None, self_store=False, **kwargs):
        """ Store the received data in this node's local hash table
        
        @param key: The hashtable key of the data
        @type key: str
        @param value: The actual data (the value associated with C{key})
        @type value: str
        @param originalPublisherID: The node ID of the node that is the
                                    B{original} publisher of the data
        @type originalPublisherID: str
        @param age: The relative age of the data (time in seconds since it was
                    originally published). Note that the original publish time
                    isn't actually given, to compensate for clock skew between
                    different nodes.
        @type age: int

        @rtype: str
        
        @todo: Since the data (value) may be large, passing it around as a buffer
               (which is the case currently) might not be a good idea... will have
               to fix this (perhaps use a stream from the Protocol class?)
        """
        # Get the sender's ID (if any)
        if originalPublisherID == None:
            if '_rpcNodeID' in kwargs:
                originalPublisherID = kwargs['_rpcNodeID']
            else:
                raise TypeError, 'No NodeID given. Therefore we can\'t store this node'

        if self_store is True and self.externalIP is not None:
            contact = Contact(self.id, self.externalIP, self.port, None, None)
            compact_ip = contact.compact_ip()
        elif '_rpcNodeContact' in kwargs:
            contact = kwargs['_rpcNodeContact']
            #print contact.address
            compact_ip = contact.compact_ip()
            #print compact_ip
        else:
            return 'Not OK'
            #raise TypeError, 'No contact info available'

        if ((self_store is False) and
            (not 'token' in value or not self.verify_token(value['token'], compact_ip))):
            #if not 'token' in value:
            #    print "Couldn't find token in value"
            #elif not self.verify_token(value['token'], contact.compact_ip()):
            #    print "Token is invalid"
            raise ValueError('Invalid or missing token')

        if 'port' in value:
            port = int(value['port'])
            if 0 <= port <= 65536:
                compact_port = str(struct.pack('>H', port))
            else:
                raise TypeError, 'Invalid port'
        else:
            raise TypeError, 'No port available'

        if 'lbryid' in value:
            if len(value['lbryid']) > constants.key_bits:
                raise ValueError, 'Invalid lbryid'
            else:
                compact_address = compact_ip + compact_port + value['lbryid']
        else:
            raise TypeError, 'No lbryid given'

        #if originalPublisherID == None:
        #if rpcSenderID != None:
        #    originalPublisherID = rpcSenderID
        #else:
        #    raise TypeError, 'No publisher specifed, and RPC caller ID not available. Data requires an original publisher.'
        #if self_store is True:
        #    print "got this far"
        now = int(time.time())
        originallyPublished = now# - age
        #print compact_address
        self._dataStore.addPeerToBlob(key, compact_address, now, originallyPublished, originalPublisherID)
        #if self_store is True:
        #    print "looks like it was successful maybe"
        return 'OK'
示例#30
0
    def datagramReceived(self, datagram, address):
        """ Handles and parses incoming RPC messages (and responses)

        @note: This is automatically called by Twisted when the protocol
               receives a UDP datagram
        """
        if datagram[0] == '\x00' and datagram[25] == '\x00':
            totalPackets = (ord(datagram[1]) << 8) | ord(datagram[2])
            msgID = datagram[5:25]
            seqNumber = (ord(datagram[3]) << 8) | ord(datagram[4])
            if msgID not in self._partialMessages:
                self._partialMessages[msgID] = {}
            self._partialMessages[msgID][seqNumber] = datagram[26:]
            if len(self._partialMessages[msgID]) == totalPackets:
                keys = self._partialMessages[msgID].keys()
                keys.sort()
                data = ''
                for key in keys:
                    data += self._partialMessages[msgID][key]
                    datagram = data
                del self._partialMessages[msgID]
            else:
                return
        try:
            msgPrimitive = self._encoder.decode(datagram)
        except encoding.DecodeError:
            # We received some rubbish here
            return
        
        message = self._translator.fromPrimitive(msgPrimitive)
        remoteContact = Contact(message.nodeID, address[0], address[1], self)
        
        # Refresh the remote node's details in the local node's k-buckets
        self._node.addContact(remoteContact)

        if isinstance(message, msgtypes.RequestMessage):
            # This is an RPC method request
            self._handleRPC(remoteContact, message.id, message.request, message.args)
        elif isinstance(message, msgtypes.ResponseMessage):
            # Find the message that triggered this response
            if self._sentMessages.has_key(message.id):
                # Cancel timeout timer for this RPC
                df, timeoutCall = self._sentMessages[message.id][1:3]
                timeoutCall.cancel()
                del self._sentMessages[message.id]

                if hasattr(df, '_rpcRawResponse'):
                    # The RPC requested that the raw response message and originating address be returned; do not interpret it
                    df.callback((message, address))
                elif isinstance(message, msgtypes.ErrorMessage):
                    # The RPC request raised a remote exception; raise it locally
                    if message.exceptionType.startswith('exceptions.'):
                        exceptionClassName = message.exceptionType[11:]
                    else:
                        localModuleHierarchy = self.__module__.split('.')
                        remoteHierarchy = message.exceptionType.split('.')
                        #strip the remote hierarchy
                        while remoteHierarchy[0] == localModuleHierarchy[0]:
                            remoteHierarchy.pop(0)
                            localModuleHierarchy.pop(0)
                        exceptionClassName = '.'.join(remoteHierarchy)
                    remoteException = None
                    try:
                        exec 'remoteException = %s("%s")' % (exceptionClassName, message.response)
                    except Exception:
                        # We could not recreate the exception; create a generic one
                        remoteException = Exception(message.response)
                    df.errback(remoteException)
                else:
                    # We got a result from the RPC
                    df.callback(message.response)
            else:
                # If the original message isn't found, it must have timed out
                #TODO: we should probably do something with this...
                pass
示例#31
0
    def test_displat_all_contacts(self):
        '''
        Method that returns a list of all contacts saved
        '''

        self.assertEqual(Contact.display_contacts(), Contact.contact_list)
示例#32
0
 def setUp(self):
     '''
     Set up method to run before each test cases
     '''
     self.new_contact = Contact('Carine', 'I. SEMWAGA', '0788206956',
                                '*****@*****.**')
示例#33
0
 def setUp(self):
     '''
     set up method that should run before each test case
     '''
     self.new_contact = Contact("Maryanne", "Njeri", "071234567",
                                "*****@*****.**")
示例#34
0
 def setUp(self):
     '''
     Set up method to run before each test cases.
     '''
     self.new_contact = Contact("James", "Muriuki", "0712345678",
                                "*****@*****.**")  # create contact object
示例#35
0
def display_contacts():
    '''
    Function that returns all the saved contacts
    '''
    return Contact.display_contacts()
示例#36
0
def check_existing_contacts(number):
    '''
    Function that check if a contact exists with that number and return a Boolean
    '''
    return Contact.contact_exist(number)
示例#37
0
 def add_contact(self, name, surname, telephone, *args, **kwargs):
     self.contact_list.append(
         Contact(name, surname, telephone, *args, **kwargs))
示例#38
0
class TestContact(unittest.TestCase):
    '''
    Test class that defines test cases for the contact class behaviours.

    Args:
        unittest.TestCase: TestCase class that helps in creating test classes

    '''
    def setUp(self):
        '''
        Set up method to run before eact test cases.

        '''
        self.new_contact = Contact('James', 'Muriuki', '0712345678',
                                   '*****@*****.**')  # create contact object

    def tearDown(self):
        '''
        tearDown method that does clean up after each test case has run.
        '''
        Contact.contact_list = []

    def test_init(self):
        '''
        test_init test case to test if the object is initialized properly
        '''

        self.assertEqual(self.new_contact.first_name, 'James')
        self.assertEqual(self.new_contact.last_name, 'Muriuki')
        self.assertEqual(self.new_contact.phone_number, '0712345678')
        self.assertEqual(self.new_contact.email, '*****@*****.**')

    def test_save_contact(self):
        '''
        test_save_contact test case to test if the contact object is saved into the contact list
        '''
        self.new_contact.save_contact()  # saving the new contact
        self.assertEqual(len(Contact.contact_list), 1)

    def test_save_multiple_contact(self):
        '''
        test_save_multiple_contact to check if we can save multiple contact objects to our contact list
        '''

        self.new_contact.save_contact()
        test_contact = Contact('Test', 'user', '0712345678',
                               '*****@*****.**')  # new contact
        test_contact.save_contact()
        self.assertEqual(len(Contact.contact_list), 2)

    def test_delete_contact(self):
        '''
        test_delete_contact to test if we an remove a contact from our contact list
        '''
        self.new_contact.save_contact()
        test_contact = Contact('Test', 'user', '0712345678',
                               '*****@*****.**')  # new contact
        test_contact.save_contact()

        self.new_contact.delete_contact()  # Deleting a contact object
        self.assertEqual(len(Contact.contact_list), 1)

    def test_find_contact_by_number(self):
        '''
        test to check if we can find a contact by phone number and display information
        '''

        self.new_contact.save_contact()
        test_contact = Contact('Test', 'user', '0711223344',
                               '*****@*****.**')  # new contact
        test_contact.save_contact()

        found_contact = Contact.find_by_number('0711223344')
        self.assertEqual(found_contact.email, test_contact.email)
示例#39
0
 def add_contact(self, username):
     contact = Contact(username)
     db.session.add(contact)
     db.session.commit()
示例#40
0
from professor import Professor
from student import Student
from contact import Contact
from person import Person

# p = Person(name='mehul', gender='m') # cannot do that!

p1 = Professor(name='mehul chopra', gender='m', subjects=['Maths', 'Programming'],\
    contact=Contact(email='*****@*****.**', mobile='0987907907'))
'''
    1) RAM 90345
    2) Professor.__init__(90345, name, gender, subjects)
'''

s1 = Student(name='jane', gender='f', roll=10, marks=90)

s1.giveAttendance()
p1.giveAttendance()
'''print(p1.getEmail())
print(p1.getMobile())

print(s1.getEmail())'''

# print(s1.getPrettyDetails())
# print(p1.getPrettyDetails())
# print(p1.name)
'''Professor and Student objects belong to a common category of people in the college.
   They share common properties (name, gender)
'''
示例#41
0
def find_contact(number):
    '''
    Function that finds a contact by number and returns the contact
    '''
    return Contact.find_by_number(number)
示例#42
0
 def add(self, name, phone_number, email):
     contact = Contact(name, phone_number, email)
     self._contacts.append(contact)
     self._save()
示例#43
0
def create_contact(fname, lname, phone, email):
    '''
    Function to create a new contact
    '''
    new_contact = Contact(fname, lname, phone, email)
    return new_contact
示例#44
0
    def test_display_all_contacts(self):

        self.assertEqual(Contact.display_contacts(), Contact.contact_list)
示例#45
0
    def test_something(self):
        kim = Contact('김일구', '010-8812-1193', '*****@*****.**', 'Seoul')

        self.assertEqual(True, True)
示例#46
0
    def test_copy_email(self):

        self.new_contact.save_contact()
        Contact.copy_email("0712345678")

        self.assertEqual(self.new_contact.email, pyperclip.paste())
示例#47
0
class TestContact(unittest.TestCase):
    '''
    Test class that defines test cases for the contact class behaviours.

    Args:
        unittest.TestCase: TestCase class that helps in creating test cases
    '''

    # Items up here .......

    def setUp(self):
        '''
        Set up method to run before each test cases.
        '''
        self.new_contact = Contact("James", "Muriuki", "0712345678",
                                   "*****@*****.**")  # create contact object

    def test_init(self):
        '''
        test_init test case to test if the object is initialized properly
        '''

        self.assertEqual(self.new_contact.first_name, "James")
        self.assertEqual(self.new_contact.last_name, "Muriuki")
        self.assertEqual(self.new_contact.phone_number, "0712345678")
        self.assertEqual(self.new_contact.email, "*****@*****.**")

    def test_save_contact(self):
        '''
        test_save_contact test case to test if the contact object is saved into
         the contact list
        '''
        self.new_contact.save_contact()  # saving the new contact
        self.assertEqual(len(Contact.contact_list), 1)

    def tearDown(self):
        '''
            tearDown method that does clean up after each test case has run.
            '''
        Contact.contact_list = []


# other test cases here

    def test_save_multiple_contact(self):
        '''
            test_save_multiple_contact to check if we can save multiple contact
            objects to our contact_list
            '''
        self.new_contact.save_contact()
        test_contact = Contact("Test", "user", "0712345678",
                               "*****@*****.**")  # new contact
        test_contact.save_contact()
        self.assertEqual(len(Contact.contact_list), 2)

    def test_delete_contact(self):
        '''
            test_delete_contact to test if we can remove a contact from our contact list
            '''
        self.new_contact.save_contact()
        test_contact = Contact("Test", "user", "0712345678",
                               "*****@*****.**")  # new contact
        test_contact.save_contact()

        self.new_contact.delete_contact()  # Deleting a contact object
        self.assertEqual(len(Contact.contact_list), 1)

    def test_find_contact_by_number(self):
        '''
        test to check if we can find a contact by phone number and display information
        '''

        self.new_contact.save_contact()
        test_contact = Contact("Test", "user", "0711223344",
                               "*****@*****.**")  # new contact
        test_contact.save_contact()

        found_contact = Contact.find_by_number("0711223344")

        self.assertEqual(found_contact.email, test_contact.email)

    def test_contact_exists(self):
        '''
        test to check if we can return a Boolean  if we cannot find the contact.
        '''

        self.new_contact.save_contact()
        test_contact = Contact("Test", "user", "0711223344",
                               "*****@*****.**")  # new contact
        test_contact.save_contact()

        contact_exists = Contact.contact_exist("0711223344")

        self.assertTrue(contact_exists)

    def test_display_all_contacts(self):
        '''
        method that returns a list of all contacts saved
        '''

        self.assertEqual(Contact.display_contacts(), Contact.contact_list)

    def test_copy_email(self):
        '''
        Test to confirm that we are copying the email address from a found contact
        '''

        self.new_contact.save_contact()
        Contact.copy_email("0712345678")

        self.assertEqual(self.new_contact.email, pyperclip.paste())
示例#48
0
'''
Created on Feb 11, 2016

@author: leo
'''
import unittest
from contact import ContactsDb, Contact
from _mysql_exceptions import OperationalError
HOST = 'localhost'
USERNAME = '******'
PASSWORD = '******'
TABLE = 'contacts'
DBNAME = 'contacts_orm_test'
testContact = Contact('Lennox', ContactsDb.MALE, '02099888999', 'self')
testContact2 = Contact('Leonard', ContactsDb.MALE, '03044556646', 'other self')


class TestDb(unittest.TestCase):
    def testDbConnect(self):
        self.assertTrue(
            ContactsDb(HOST, USERNAME, PASSWORD, DBNAME, TABLE).connect())
        pass

    def testWrongPasswordForConnect(self):
        self.assertRaises(
            OperationalError,
            ContactsDb(HOST, USERNAME, 'wrongpassword', DBNAME, TABLE).connect)


class ContactSaveTest(unittest.TestCase):
    def setUp(self):
示例#49
0
    def datagramReceived(self, datagram, address):
        """ Handles and parses incoming RPC messages (and responses)

        @note: This is automatically called by Twisted when the protocol
               receives a UDP datagram
        """

        if datagram[0] == '\x00' and datagram[25] == '\x00':
            totalPackets = (ord(datagram[1]) << 8) | ord(datagram[2])
            msgID = datagram[5:25]
            seqNumber = (ord(datagram[3]) << 8) | ord(datagram[4])
            if msgID not in self._partialMessages:
                self._partialMessages[msgID] = {}
            self._partialMessages[msgID][seqNumber] = datagram[26:]
            if len(self._partialMessages[msgID]) == totalPackets:
                keys = self._partialMessages[msgID].keys()
                keys.sort()
                data = ''
                for key in keys:
                    data += self._partialMessages[msgID][key]
                    datagram = data
                del self._partialMessages[msgID]
            else:
                return
        try:
            msgPrimitive = self._encoder.decode(datagram)
        except encoding.DecodeError:
            # We received some rubbish here
            return
        except IndexError:
            log.warning("Couldn't decode dht datagram from %s", address)
            return

        message = self._translator.fromPrimitive(msgPrimitive)
        remoteContact = Contact(message.nodeID, address[0], address[1], self)

        now = time.time()
        contact_history = self._history_rx.get(address, [])
        if len(contact_history) > 1000:
            contact_history = [x for x in contact_history if now - x[1] < 1.0]
        contact_history.append((len(datagram), time.time()))
        self._history_rx[address] = contact_history
        bytes_rx = self._bytes_rx.get(address, 0)
        bytes_rx += len(datagram)
        self._bytes_rx[address] = bytes_rx
        if address not in self.unique_contacts:
            self._unique_contacts.append(address)

        # Refresh the remote node's details in the local node's k-buckets
        self._node.addContact(remoteContact)
        if isinstance(message, msgtypes.RequestMessage):
            # This is an RPC method request
            self._handleRPC(remoteContact, message.id, message.request,
                            message.args)

        elif isinstance(message, msgtypes.ResponseMessage):
            # Find the message that triggered this response
            if message.id in self._sentMessages:
                # Cancel timeout timer for this RPC
                df, timeoutCall = self._sentMessages[message.id][1:3]
                timeoutCall.cancel()
                del self._sentMessages[message.id]

                if hasattr(df, '_rpcRawResponse'):
                    # The RPC requested that the raw response message
                    # and originating address be returned; do not
                    # interpret it
                    df.callback((message, address))
                elif isinstance(message, msgtypes.ErrorMessage):
                    # The RPC request raised a remote exception; raise it locally
                    remoteException = Exception(message.response)
                    df.errback(remoteException)
                else:
                    # We got a result from the RPC
                    df.callback(message.response)
            else:
                # If the original message isn't found, it must have timed out
                # TODO: we should probably do something with this...
                pass
示例#50
0
 def testRetrieveContactById(self):
     contactId = 1
     #check if contact #1 exist
     contact = Contact.retrieve(contactId)
     self.failUnless(contact)
     self.assertEqual(contactId, contact.id)
示例#51
0
class TestContact(unittest.TestCase):
    '''
    Test class that desfines test cases for the contact class behaviours

    Args:
        unittest.TestCase: TestCase class that helps in creating test cases
    '''
    def setUp(self):
        '''
        Set up method to run before each test cases
        '''
        self.new_contact = Contact('Carine', 'I. SEMWAGA', '0788206956',
                                   '*****@*****.**')
        # Create contact object

    def test_init(self):
        '''
        test_init test case to test if the object is initialized properly
        '''
        self.assertEqual(self.new_contact.first_name, 'Carine')
        self.assertEqual(self.new_contact.last_name, 'I. SEMWAGA')
        self.assertEqual(self.new_contact.phone_number, '0788206956')
        self.assertEqual(self.new_contact.email, '*****@*****.**')

    def test_save_contact(self):
        '''
        test_save_contact test case to test if the contact object is savd into the contact list
        '''
        self.new_contact.save_contact()  #saving the new contact
        self.assertEqual(len(Contact.contact_list), 1)

    # SetUp and class creation up here

    def tearDown(self):
        '''
        tearDown method that does clean up after each test has run
        '''
        Contact.contact_list = []

    # Other test cases here
    def test_save_multiple_contact(self):
        '''
        test_save_multiple_contact to check if we can save multiple contact
        '''
        self.new_contact.save_contact()
        test_contact = Contact('Test', 'user', '0712345678',
                               '*****@*****.**')  # new contact
        test_contact.save_contact()
        self.assertEqual(len(Contact.contact_list), 2)

    #More test
    def test_delete_contact(self):
        '''
        test_delete_contact to test if we can remove a contact from our contact list
        '''
        self.new_contact.save_contact()
        test_contact = Contact('Test', 'user', '0712345678',
                               '*****@*****.**')  # new contact
        test_contact.save_contact()

        self.new_contact.delete_contact()  #Deleting a contact object
        self.assertEqual(len(Contact.contact_list), 1)

    def test_find_contact_by_number(self):
        '''
        test to check if we can find a contact by phone number and display information
        '''

        self.new_contact.save_contact()
        test_contact = Contact('Test', 'user', '0712345678',
                               '*****@*****.**')  # new contact
        test_contact.save_contact()

        found_contact = Contact.find_by_number('0712345678')
        self.assertEqual(found_contact.email, test_contact.email)

    def test_contact_exists(self):
        '''
        test to check if we canreturn a Booleanif we cannot find the contact.
        '''

        self.new_contact.save_contact()
        test_contact = Contact('Test', 'user', '0712345678',
                               '*****@*****.**')  # new contact
        test_contact.save_contact()

        contact_exists = Contact.contact_exists('0712345678')

        self.assertTrue(contact_exists)

    def test_displat_all_contacts(self):
        '''
        Method that returns a list of all contacts saved
        '''

        self.assertEqual(Contact.display_contacts(), Contact.contact_list)

    def test_copy_email(self):
        '''
        Test to confirm that we are copying the email address from a found contact
        '''
        self.new_contact.save_contact()
        Contact.copy_email('0712345678')

        self.assertEqual(self.new_contact.email, pyperclip.paste())
示例#52
0
 def testRetrieveAll(self):
     contacts = Contact.retrieveAll()
     self.assertEquals(len(contacts), 2)
示例#53
0
from login import Login
from remote import Remote
from music import Music

app = flask.Flask(__name__)
app.secret_key = settings.secret_key

# Routes
app.add_url_rule('/',
                 view_func=Main.as_view('main'),
                 methods=["GET"])
app.add_url_rule('/about/',
                 view_func=About.as_view('about'),
                 methods=["GET"])
app.add_url_rule('/contact/',
                 view_func=Contact.as_view('contact'),
                 methods=["GET"])
app.add_url_rule('/index/',
                 view_func=Index.as_view('index'),
                 methods=["GET"])
app.add_url_rule('/<page>/',
                 view_func=Main.as_view('main'),
                 methods=["GET"])
app.add_url_rule('/login/',
                 view_func=Login.as_view('login'),
                 methods=["GET", "POST"])
app.add_url_rule('/remote/',
                 view_func=Remote.as_view('remote'),
                 methods=["GET", "POST"])
app.add_url_rule('/music/',
                 view_func=Music.as_view('music'),
示例#54
0
 def setUp(self):
     cdb = ContactsDb(HOST, USERNAME, PASSWORD, DBNAME, TABLE)
     Contact.connect(cdb)
     testContact.save()
示例#55
0
 def delete_contact(self):
     print('Please enter ID of contact to delete: ')
     id = input()
     contact = Contact.get_by_id(id)
     contact.delete_instance()
示例#56
0
 def tearDown(self):
     Contact.clear()
示例#57
0
def copy_email(number):
    '''
    Function that copies email from a contact
    '''
    return Contact.copy_email(number)
 def setUp(self):
     self.contact = Contact()
示例#59
0
class TestContact(unittest.TestCase):
    def setUp(self):
        def tearDown(self):

            Contact.contact_list = []

        self.new_contact = Contact("James", "Muriuki", "0712345678",
                                   "*****@*****.**")

    def test_init(self):

        self.assertEqual(self.new_contact.first_name, "James")
        self.assertEqual(self.new_contact.last_name, "Muriuki")
        self.assertEqual(self.new_contact.phone_number, "0712345678")
        self.assertEqual(self.new_contact.email, "*****@*****.**")

    def test_save_contact(self):

        self.new_contact.save_contact()
        self.assertEqual(len(Contact.contact_list), 7)

    def test_save_multiple_contact(self):

        self.new_contact.save_contact()
        test_contact = Contact("Test", "user", "0712345678",
                               "*****@*****.**")  # new contact
        test_contact.save_contact()
        self.assertEqual(len(Contact.contact_list), 9)

    def test_delete_contact(self):

        self.new_contact.save_contact()
        test_contact = Contact("Test", "user", "0712345678",
                               "*****@*****.**")  # new contact
        test_contact.save_contact()

        self.new_contact.delete_contact()  # Deleting a contact object
        self.assertEqual(len(Contact.contact_list), 4)

    def test_find_contact_by_number(self):

        self.new_contact.save_contact()
        test_contact = Contact("Test", "user", "0711223344",
                               "*****@*****.**")  # new contact
        test_contact.save_contact()

        found_contact = Contact.find_by_number("0711223344")

        self.assertEqual(found_contact.email, test_contact.email)

    def test_contact_exists(self):

        self.new_contact.save_contact()
        test_contact = Contact("Test", "user", "0711223344",
                               "*****@*****.**")  # new contact
        test_contact.save_contact()

        contact_exists = Contact.contact_exist("0711223344")

        self.assertTrue(contact_exists)

    def test_display_all_contacts(self):

        self.assertEqual(Contact.display_contacts(), Contact.contact_list)

    def test_copy_email(self):

        self.new_contact.save_contact()
        Contact.copy_email("0712345678")

        self.assertEqual(self.new_contact.email, pyperclip.paste())
def main(args):
    sys.argv=args
    args= docopt(__doc__)
    contact = Contact()
    # contact.set_bday(args["--bday"])
    schema = Schema({
        '--contact_id': Or(None,And(Use(int),Use(contact.set_cid, error='id is not correct, it should be integer number'))),
        '--first_name': Or(None,Use(contact.set_fname, error='fname is not correct')),
        '--last_name': Or(None,Use(contact.set_lname, error='lname is not correct')),
        '--middle_name': Or(None,Use(contact.set_mname, error='mname is not correct')),
        '--phone': Or(None,Use(contact.set_phone, error='phone is not correct')),
        '--bday': Or(None,Use(contact.set_bday, error='birtday is not correct it should be one of the formats ' + str(contact.bday_types))),
        '--data': Or(None,Use(set_data, error='name was not correct')),
        '--reverse': Or(None,True,False),
        '--replace': Or(None,True,False),
        '--sort': Or(None,"fname","lname","mname","phone","bday", error="--sort should be one of the fname,lname,mname,phone,bday"),
        'add': Or(False,True),
        'del': Or(False, True),
        'find': Or(False,True),
        'list': Or(False,True),
        })
    try:
        schema.validate(args)
    except SchemaError as e:
        exit(e)
    try:
        connection = sqlite3.connect(database)
        c = connection.cursor()
        c.execute("create table contacts(id integer primary key autoincrement, fname text, lname text, mname text, phone text, bday text)")
        print("new database " + database + " was created")
    except sqlite3.Error as e:
        print("Existing database " + database)

    if args["add"]:
        added, phoneexist, comment = contact.add(contact, c, args)
        if added:
            print(comment+" " + str(contact.get_tuple()))
        else:
            print(comment)
    elif args["find"]:
        finded=contact.find(contact, c)
        if finded:
            print(tabulate(finded, headers=["Id","first name","last name","middle name","phone","birthday date"]))
        else:
            print("there is no any contact "+(("like:"+str(contact)) if str(contact) else ""))
    elif args["del"]:
        result, string=contact.delete(contact, c)
        print(string)
        if result:
            for r in result:
                print(r)
        else:
            sys.exit(-1)
    elif args["list"]:
        result = contact.lst(args, c)
        if result:
            print(tabulate(result, headers=["ID","first name","last name","middle name","phone","birthday date"]))
        else:
            print("there is empty database="+database)

    else:
        remind=contact.reminder(c)
        print("This contact will have their birthdays in this and next months:")
        if remind:
            print(tabulate(remind, headers=["Id","first name","last name","middle name","phone","birthday date"]))

    connection.commit()
    connection.close()