Пример #1
0
    def _set_p_hash_kind(self, hashkind):
        """
        Setting the hash (as an object) used for futur operation on it.

        :Example: PST._set_p_hash_kind("md5")

        .. seealso:: Hash.py Object to get the available hashs.

        """
        self.p_hash_kind = Hash(hashkind)
Пример #2
0
 def login(self, instance):
     if verify(self.ut.text,
               Hash(self.pt.text)):  #if userID and passwords match
         weight, machineid, endtime = getData(
             self.ut.text, ['weight', 'machineid', 'endtime'
                            ])  #gets current wash info of the user
         timing, studentid = getState(
             globalMachine,
             ['state', 'studentid'
              ])  #gets current userids and state of washing machine
         if weight == None:  #if user has no current washes
             weight = [globalWeight]
             machineid = [globalMachine]
             if timing == 0:  #of no laudry in the machine, puts time of putting laundry
                 endtime = [time() + washTime + timeOut]
             else:  #uses the first user's time of putting laundry
                 endtime = [timing + washTime + timeOut]
         else:  #adds new wash info to current washes
             weight += [globalWeight]
             machineid += [globalMachine]
             if timing == 0:
                 endtime += [time() + washTime + timeOut]
             else:
                 endtime += [timing + washTime + timeOut]
         if studentid == None:  #if machine is empty, create the user list
             studentid = [self.ut.text]
         else:  #add user info to user list
             studentid += [self.ut.text]
         putData(self.ut.text,
                 weight=weight,
                 machineid=machineid,
                 endtime=endtime,
                 debt=globalCost,
                 pmstate=0)  #updates users data to firebase
         if globalState == -1:  #if last user (washing machine starts wash immediately after this user), updates info accordingly
             putState(globalMachine,
                      door=1,
                      state=-1,
                      weight=globalWeight,
                      studentid=studentid)
         elif getState(
                 globalMachine, 'state'
         ) == 0:  #if first user, puts time of putting laundry and updates info accordingly
             putState(globalMachine,
                      door=1,
                      state=time(),
                      weight=globalWeight,
                      studentid=studentid)
         else:  #if neither, keeps first user timing and updates rest of info accordingly
             putState(globalMachine,
                      door=1,
                      weight=globalWeight,
                      studentid=studentid)
         global globalState
         globalState = timing
         self.manager.current = 'wash'
     else:
         self.ut.text = ''
         self.pt.text = ''
         self.fail.text = 'Incorrect User ID or Password'
Пример #3
0
 def calcHashAndSize(self):
     if os.path.isfile(self.fileName + ".fileDat"):
         with open(self.fileName + ".fileDat", 'rb') as f:
             fd = pickle.load(f)
             h, fileSize = fd.fileHash, fd.fileSize
     else:
         h = Hash()
         BUF_SIZE = 65536
         fileSize = 0
         with open(self.fileName, 'rb') as f:
             while True:
                 data = f.read(BUF_SIZE)
                 if not data:
                     break
                 h.update(data)
                 fileSize += len(data)
         h = h.calculateHash()
     return h, fileSize
Пример #4
0
    def gen_hash_file(self, hashdata):
        headers = set([f for h in hashdata for f in h['headers']])
        classes = [Hash(p['name'], p['docstring']) for p in hashdata]
        self.objects.extend(classes)
        self.hashes = classes

        self.write_class_file(self.hash_file, classes, headers)
        self.write_doc_file(self.hash_doc_file, "Hashes",
                            docstrings.hash_example, classes)
Пример #5
0
    def test_behavior(self):
        """Test basic behavior."""
        h = Hash(1423, 197)
        h.insert(55, 'fifty five')
        self.assertEqual((55, 'fifty five'), h.search('fifty five'))
        self.assertEqual((55, 'fifty five'), h.table[808])
        self.assertEqual('A', h.state[808])

        h.insert(1234, 'one two three four')
        self.assertEqual((1234, 'one two three four'),
                         h.search('one two three four'))
Пример #6
0
 def __init__(self, dato, f="", c="", ids=0):
     self.dato = dato
     self.sig = None
     self.ant = None
     self.arriba = None
     self.abajo = None
     self.atras = None
     self.frente = None
     self.f = f
     self.c = c
     self.id = ids
     self.tablaHash = Hash()
Пример #7
0
 def createBlock(self,buffer):
     self.__previousHashPointer=self.lastHashPointer
     if(len(self.__blockChain)==0):
         block=Block(None,None)
     else:
         block=Block(self.__previousHashPointer.pointer,self.__previousHashPointer.previousHash) 
     
     block.addTransactions(buffer)
     block.setBlockHash()
     self.lastHashPointer=HashPointer(block,Hash(block)) 
     #signing
     self.lastHashPointer.Sign(self.scroogeSign(str(self.lastHashPointer)))
     self.__blockChain.append(block)  
Пример #8
0
    def __init__(self, sample, cutList='1', branches=None, inputFolder=None, tmpFolder=None, outputFolder=None, chunkNumber=-1, splitFilesChunks=-1, splitFilesChunkSize=-1, debug=False, fileList=None, cutSequenceMode='AND', name='', config=None, fileLocator=None):
        self.config = config
        self.fileLocator = fileLocator if fileLocator is not None else FileLocator(config=self.config)
        self.debug = debug or ('XBBDEBUG' in os.environ)

        # SAMPLE
        if isinstance(sample, Sample):
            # sample passed as Sample object
            # count number of chunks the cached data is split into
            defaultChunkSize = int(config.get('General', 'mergeCachingSize')) if config.has_option('General', 'mergeCachingSize') else 100
            splitFilesChunkSize = sample.mergeCachingSize if sample.mergeCachingSize > 0 else defaultChunkSize
            splitFilesChunks = SampleTree({'name': sample.identifier, 'folder': inputFolder}, countOnly=True, splitFilesChunkSize=splitFilesChunkSize, config=config, verbose=self.debug, fileLocator=self.fileLocator).getNumberOfParts()
            # if sample passed as object, it can be a 'subsample' and habe different name and identifier
            self.sample = sample.name
            self.sampleIdentifier = sample.identifier
            if self.debug:
                print ("INFO: use sample=", sample.name, " #parts = ", splitFilesChunks)
        else:
            # sample identifier passed as string
            self.sample = sample
            self.sampleIdentifier = sample
        self.name = name

        # CUTS
        self.cutList = cutList
        self.cutSequenceMode = cutSequenceMode
        self.minCut = SampleTree.findMinimumCut(self.cutList, cutSequenceMode=self.cutSequenceMode)

        # PATHS
        self.inputFolder = inputFolder
        self.outputFolder = (config.get('Directories', 'tmpSamples') if config else 'cache/') if outputFolder is None else outputFolder
        self.tmpFolder = (config.get('Directories', 'scratch') if config else 'tmp/') if tmpFolder is None else tmpFolder
        self.cachedFileNames = []
        self.tmpFiles = []
        self.outputFileNameFormat = '{outputFolder}/tmp_{hash}_{part}of{parts}.root'

        # BRANCHES and chunk information
        self.branches = branches
        self.branchesForHash = None     # for now make hash independent of selecte branches 
        self.hash = Hash(sample=sample, minCut=self.minCut, branches=self.branchesForHash, splitFilesChunkSize=splitFilesChunkSize, debug=False, inputPath=self.inputFolder).get()
        self.chunkNumber = chunkNumber
        self.splitFilesChunks = splitFilesChunks if splitFilesChunks > 1 else 1
        self.splitFilesChunkSize = splitFilesChunkSize
        
        # identifier is just used as an arbitrary name for print-out
        cutUsedForIdentifier = (self.minCut if len(self.minCut) < 60 else self.minCut[0:50] + '...').replace(' ', '')
        self.identifier = '{sample}[{cut}]of{parts}'.format(sample=self.sample, cut=cutUsedForIdentifier, parts=self.splitFilesChunks)
        self.sampleTree = None
        self.isCachedChecked = False

        self.createFolders()
Пример #9
0
def GetInitialFile():
    """Pega o arquivo inicial e insere seu conteudo numa Hash"""
    LocalOnList = 0
    StringToPass = GetFileContent()
    Dictionary = Hash()
    for i in StringToPass:
        Temp = AppliesRE(i[0])
        Temp = list(set(Temp)) #Remove todas as ocorrencias repetidas de um tweet
        Value = int(i[1])
        for Word in Temp:
            InsertOnHash(Dictionary ,Word, Value, LocalOnList)
        LocalOnList += 1
    ReturningValue = DictAndText(Dictionary, LocalOnList)
    WriteTXT(StringToPass, 'w', ReturningValue.TextFile)
    return ReturningValue
Пример #10
0
 def autenticarSesion(self, datosCifrado):
      datos = Hash().descifrar(datosCifrado, self.configCifrador.CLAVE_PUBLICA, self.configCifrador.SEMILLA, self.configCifrador.ITERACIONES)
      usuario = datos.split(TAG2)[0]
      clave = datos.split(TAG2)[1]
      if exists (self.configCifrador.ARCHIVO_USUARIOS_CIFRADO):
         archivoCifrado = open(self.configCifrador.ARCHIVO_USUARIOS_CIFRADO,"r")
      else:
         print "No existe archivo de cifrado."
         sys.exit(1)
      listaUsuarios = archivoCifrado.read().split(self.configCifrador.SEP1)
      acceso=0
      for user in listaUsuarios:
          if len(user):      
            datos = Hash().descifrar(user, self.configCifrador.CLAVE_PUBLICA, self.configCifrador.SEMILLA, self.configCifrador.ITERACIONES)
            usuarioArchivo = datos.split(TAG2)[0]
            claveArchivo = datos.split(TAG2)[1]
            if usuarioArchivo == usuario and claveArchivo == clave:
                 acceso=1
                 break
      archivoCifrado.close()
      return usuario, acceso
Пример #11
0
 def __init__(self):
     self.list = Lista_s()
     self.abb = Arbol_b()
     self.avl = Avl_Tree()
     self.hash = Hash(100)
Пример #12
0
class Estructuras:
    def __init__(self):
        self.list = Lista_s()
        self.abb = Arbol_b()
        self.avl = Avl_Tree()
        self.hash = Hash(100)

    def menu_list(self, opcion):
        if (opcion == 1):
            nombre, apellido, telefono, mail = agregar_datos()
            self.list._insertar(nombre, apellido, telefono, mail)
            return (False)
        if (opcion == 2):
            print("---eliminar contacto--------------")
            print("ingrese apellido:")
            ape = input()
            self.list.eliminar(ape)
            print("----------------------------------")
            return (False)
        if (opcion == 3):
            print("---imprimir contacto--------------")
            print("ingrese apellido:")
            ape = input()
            self.list.imprimir_contacto(ape)
            print("----------------------------------")
            return (False)
        if (opcion == 4):
            print("---Mostrando Lista de contactos---")
            self.list.imprimir_todos()
            print("----------------------------------")
            return (False)
        if (opcion == 5):
            print("---exit---------------------------")
            print("saliendo de lista enlazada")
            print("----------------------------------")
            return (True)

    def menu_2_3(self, opcion):
        if (opcion == 1):  #agregar contacto
            print("---agregar contacto---------------")
            nombre, apellido, telefono, mail = agregar_datos()
            self.arbol_23.insertar(nombre, apellido, telefono, mail)
            print("----------------------------------")
            return (False)
        if (opcion == 2):
            print("---eliminar contacto--------------")
            print("ingrese apellido:")
            ape = input()
            self.arbol_23.remove(ape)
            print("----------------------------------")
            return (False)
        if (opcion == 3):
            print("---imprimir contacto--------------")
            print("ingrese apellido:")
            ape = input()
            self.arbol_23.mostrar_contacto(ape)
            print("----------------------------------")
            return (False)
        if (opcion == 4):
            print("---Mostrando Lista de contactos---")
            self.arbol_23.mostrar_todos()
            print("----------------------------------")
            return (False)
        if (opcion == 5):
            print("---exit---------------------------")
            print("saliendo de Arbol 2-3")
            print("----------------------------------")
            return (True)

    def menu_abb(self, opcion):
        if (opcion == 1):
            print("---agregar contacto---------------")
            nombre, apellido, telefono, mail = agregar_datos()
            self.abb.add(nombre, apellido, telefono, mail)
            print("----------------------------------")
            return (False)
        if (opcion == 2):
            print("---eliminar contacto--------------")
            print("ingrese apellido:")
            ape = input()
            self.abb.delete(ape)
            print("----------------------------------")
            return (False)
        if (opcion == 3):
            print("---imprimir contacto--------------")
            print("ingrese apellido:")
            ape = input()
            self.abb.print_contact(ape)
            print("----------------------------------")
            return (False)
        if (opcion == 4):
            print("---Mostrando Lista de contactos---")
            self.abb.in_order(self.abb.get_root())
            print("----------------------------------")
            return (False)
        if (opcion == 5):
            print("---exit---------------------------")
            print("saliendo de Arbol binario de busqueda")
            print("----------------------------------")
            return (True)

    def menu_avl(self, opcion):
        if (opcion == 1):  #agregar contacto
            print("---agregar contacto---------------")
            nombre, apellido, telefono, mail = agregar_datos()
            self.avl.add(nombre, apellido, telefono, mail)
            print("----------------------------------")
            return (False)
        if (opcion == 2):
            print("---eliminar contacto--------------")
            print("ingrese apellido:")
            ape = input()
            self.avl.delete(ape)
            print("----------------------------------")
            return (False)
        if (opcion == 3):
            print("---imprimir contacto--------------")
            print("ingrese apellido:")
            ape = input()
            self.avl.print_contact(ape)
            print("----------------------------------")
            return (False)
        if (opcion == 4):
            print("---Mostrando Lista de contactos---")
            self.avl.in_order(self.avl.get_root())
            print("----------------------------------")
            return (False)
        if (opcion == 5):
            print("---exit---------------------------")
            print("saliendo de Arbol AVL")
            print("----------------------------------")
            return (True)

    def menu_hash(self, opcion):
        if (opcion == 1):
            print("---agregar contacto---------------")
            nombre, apellido, telefono, mail = agregar_datos()
            self.hash.put(nombre, apellido, telefono, mail)
            print("----------------------------------")
            return (False)
        if (opcion == 2):
            print("---eliminar contacto--------------")
            print("ingrese apellido:")
            ape = input()
            self.hash.H_eliminar(ape)
            print("----------------------------------")
            return (False)
        if (opcion == 3):
            print("---imprimir contacto--------------")
            print("ingrese apellido:")
            ape = input()
            self.hash.H_imprimir_contacto(ape)
            print("----------------------------------")
            return (False)
        if (opcion == 4):
            print("---Mostrando Lista de contactos---")
            self.hash.H_imprimir_todo()
            print("----------------------------------")
            return (False)
        if (opcion == 5):
            print("---exit---------------------------")
            print("saliendo de Hash")
            print("----------------------------------")
            return (True)
Пример #13
0
    print("______________________ ")
    print("1. Linear Probing ")
    print("2. Double Hashing ")
    print("3. Hybrid (Combination of option 2 and 3)")
    print("\n")
    choice = int(input("Choose an option: "))
    return choice


def userInput():
    userInput = input("Insert the number between 1-100: ")
    return userInput


if __name__ == "__main__":
    h = Hash(10)
    counter = 0
    choice = menu()
    if (choice == 1):
        while counter < 7:
            num = int(userInput())
            h.linearProbing(num, num, 1)
            h.displayHash()
            counter += 1
    elif (choice == 2):
        while counter < 7:
            h.doubleHashing(int(userInput()))
            h.displayHash()
            counter += 1
    elif (choice == 3):
        while counter < 7:
Пример #14
0
from matDispersa import MatrizDispersa
from Hash import Hash
from ListaDoble import ListaDoble

md = MatrizDispersa()
h = Hash()
#admin
#pass: admin123
"""
md.insertar("4500","Noviembre","3")
md.insertar("4500","Noviembre","25")
md.insertar("3220","Junio","10")
md.insertar("5000","Septiembre","9")
"""
"""
md.insertar("928","Abril","5")
md.insertar("2020","Junio","1")
#md.insertar("2020","Abril","7")
"""
"""

md.insertar("2010","Junio","2")
md.insertar("2016","Abril","20")
#md.insertar("2020","Mayo","31")

md.insertar("2017","Marzo","14")
md.insertar("2017","Marzo","4")
md.insertar("2017","Marzo","24")
md.insertar("2017","Marzo","15")

md.insertar("2010","Marzo","8")
Пример #15
0
from Hash import Hash

s = Hash(10)
print(s.list)

print(s.hashFunct('pork'))
s.insert('Steve', 24601)
print(s.list)
Пример #16
0
            img0, img1, img2 = self.__getitem__(len(self.imageFolderDataset))
            self.train_dataloader.append((img0, img1, img2))


if __name__ == '__main__':
    # 测试次数
    test_size = 1
    print('Start preparing the data...')
    #colo初始化
    colo = Color()

    # 直方图
    hio = Histogram()

    #hash
    has = Hash()

    #CDH
    cdh = CDH()

    #MTH
    mth = MTH()

    #数据读入
    train_data = Dataset(set_size=test_size, batch_size=1)
    train_data.classed_pack()
    print('Finish preparing the data...')

    match_err = [
        0,
        0,
Пример #17
0
class Paste(object):
    """
    This class representing a Paste as an object.
    When created, the object will have by default some "main attributes"
    such as the size or the date of the paste already calculated, whereas other
    attributes are not set and need to be "asked to be calculated" by their
    methods.
    It was design like this because some attributes take time to be calculated
    such as the langage or the duplicate...

    :Example:

    PST = Paste("/home/2013/ZEeGaez5.gz")

    """
    def __init__(self, p_path):

        configfile = os.path.join(os.environ['AIL_BIN'], 'packages/config.cfg')
        if not os.path.exists(configfile):
            raise Exception('Unable to find the configuration file. \
                            Did you set environment variables? \
                            Or activate the virtualenv.')

        cfg = ConfigParser.ConfigParser()
        cfg.read(configfile)
        self.cache = redis.StrictRedis(host=cfg.get("Redis_Queues", "host"),
                                       port=cfg.getint("Redis_Queues", "port"),
                                       db=cfg.getint("Redis_Queues", "db"))
        self.store = redis.StrictRedis(host=cfg.get("Redis_Data_Merging",
                                                    "host"),
                                       port=cfg.getint("Redis_Data_Merging",
                                                       "port"),
                                       db=cfg.getint("Redis_Data_Merging",
                                                     "db"))

        self.p_path = p_path
        self.p_name = os.path.basename(self.p_path)
        self.p_size = round(os.path.getsize(self.p_path) / 1024.0, 2)
        self.p_mime = magic.from_buffer(self.get_p_content(), mime=True)

        # Assuming that the paste will alway be in a day folder which is itself
        # in a month folder which is itself in a year folder.
        # /year/month/day/paste.gz
        var = self.p_path.split('/')
        self.p_date = Date(var[-4], var[-3], var[-2])
        self.p_source = var[-5]

        self.p_encoding = None
        self.p_hash_kind = None
        self.p_hash = None
        self.p_langage = None
        self.p_nb_lines = None
        self.p_max_length_line = None

    def get_p_content(self):
        """
        Returning the content of the Paste

        :Example:

        PST.get_p_content()

        """

        paste = self.cache.get(self.p_path)
        if paste is None:
            with gzip.open(self.p_path, 'rb') as f:
                paste = f.read()
                self.cache.set(self.p_path, paste)
                self.cache.expire(self.p_path, 300)
        return paste

    def get_p_content_as_file(self):
        return cStringIO.StringIO(self.get_p_content())

    def get_lines_info(self):
        """
        Returning and setting the number of lines and the maximum lenght of the
        lines of the paste.

        :return: tuple (#lines, max_length_line)

        :Example: PST.get_lines_info()

        """
        if self.p_nb_lines is None or self.p_max_length_line is None:
            max_length_line = 0
            f = self.get_p_content_as_file()
            line_id = 0
            for line_id, line in enumerate(f):
                length = len(line)
                if length >= max_length_line:
                    max_length_line = length
            f.close()
            self.p_nb_lines = line_id
            self.p_max_length_line = max_length_line
        return (self.p_nb_lines, self.p_max_length_line)

    def _get_p_encoding(self):
        """
        Setting the encoding of the paste.

        :Example: PST._set_p_encoding()

        """
        return self.p_mime

    def _set_p_hash_kind(self, hashkind):
        """
        Setting the hash (as an object) used for futur operation on it.

        :Example: PST._set_p_hash_kind("md5")

        .. seealso:: Hash.py Object to get the available hashs.

        """
        self.p_hash_kind = Hash(hashkind)

    def _get_p_hash(self):
        """
        Setting the hash of the paste as a kind of "uniq" identificator

        :return: hash string (md5, sha1....)

        :Example: PST._get_p_hash()

        .. note:: You need first to "declare which kind of hash you want to use
        before using this function
        .. seealso:: _set_p_hash_kind("md5")

        """
        self.p_hash = self.p_hash_kind.Calculate(self.get_p_content())
        return self.p_hash

    def _get_p_language(self):
        """
        Returning and setting the language of the paste (guessing)

        :Example: PST._get_p_language()

        ..note:: The language returned is purely guessing and may not be accurate
        if the paste doesn't contain any human dictionnary words
        ..seealso: [email protected]:saffsd/langid.py.git

        """
        identifier = LanguageIdentifier.from_modelstring(model,
                                                         norm_probs=True)
        return identifier.classify(self.get_p_content())

    def _get_p_hash_kind(self):
        return self.p_hash_kind

    def _get_p_date(self):
        return self.p_date

    def _get_hash_lines(self, min=1, start=1, jump=10):
        """
        Returning all the lines of the paste hashed.

        :param min: -- (int) Minimum line length to be hashed.
        :param start: -- (int) Number the line where to start.
        :param jump: -- (int) Granularity of the hashing 0 or 1 means no jumps
        (Maximum Granularity)

        :return: a set([]) of hash.

        .. warning:: Using a set here mean that this function will only return uniq hash.

        If the paste is composed with 1000 time the same line, this function will return
        just once the line.

        This choice was made to avoid a certain redundancy and useless hash checking.

        :Example: PST._get_hash_lines(1, 1, 0)

        .. note:: You need first to "declare which kind of hash you want to use
        before using this function
        .. seealso:: _set_p_hash_kind("md5")

        """
        S = set([])
        f = self.get_p_content_as_file()
        for num, line in enumerate(f, start):
            if len(line) >= min:
                if jump > 1:
                    if (num % jump) == 1:
                        S.add(self.p_hash_kind.Calculate(line))
                else:
                    S.add(self.p_hash_kind.Calculate(line))
        return S

    def is_duplicate(self, obj, min=1, percent=50, start=1, jump=10):
        """
        Returning the percent of similarity with another paste.
        ( Using the previous hashing method )

        :param obj: (Paste) The paste to compare with
        :param min: -- (int) Minimum line length to be hashed.
        :param percent: -- (int)
        :param start: -- (int) Number the line where to start.
        :param jump: -- (int) Granularity of the hashing 0 or 1 means no jumps
        (Maximum Granularity)

        :return: (tuple) (bool, percent)

        :Example:
        PST.is_duplicate(PST)

        >>> return (True, 100.0)

        ..seealso: _get_hash_lines()

        """

        set1 = self._get_hash_lines(min, start, jump)
        set2 = obj._get_hash_lines(min, start, jump)

        inter = set.intersection(set1, set2)

        numerator = len(inter)
        denominator = float((len(set1) + len(set2)) / 2)

        try:
            var = round((numerator / denominator) * 100, 2)
        except ZeroDivisionError:
            var = 0.0

        if var >= percent:
            return True, var
        else:
            return False, var

    def save_all_attributes_redis(self, key=None):
        """
        Saving all the attributes in a "Redis-like" Database (Redis, LevelDB)

        :param r_serv: -- Connexion to the Database.
        :param key: -- Key of an additionnal set.

        Example:
        import redis

        r_serv = redis.StrictRedis(host = 127.0.0.1, port = 6739, db = 0)

        PST = Paste("/home/Zkopkmlk.gz")
        PST.save_all_attributes_redis(r_serv)

        """
        # LevelDB Compatibility
        p = self.store.pipeline(False)
        p.hset(self.p_path, "p_name", self.p_name)
        p.hset(self.p_path, "p_size", self.p_size)
        p.hset(self.p_path, "p_mime", self.p_mime)
        # p.hset(self.p_path, "p_encoding", self.p_encoding)
        p.hset(self.p_path, "p_date", self._get_p_date())
        p.hset(self.p_path, "p_hash_kind", self._get_p_hash_kind())
        p.hset(self.p_path, "p_hash", self.p_hash)
        # p.hset(self.p_path, "p_langage", self.p_langage)
        # p.hset(self.p_path, "p_nb_lines", self.p_nb_lines)
        # p.hset(self.p_path, "p_max_length_line", self.p_max_length_line)
        # p.hset(self.p_path, "p_categories", self.p_categories)
        p.hset(self.p_path, "p_source", self.p_source)
        if key is not None:
            p.sadd(key, self.p_path)
        else:
            pass
        p.execute()

    def save_attribute_redis(self, attr_name, value):
        """
        Save an attribute as a field
        """
        if type(value) == set:
            self.store.hset(self.p_path, attr_name, json.dumps(list(value)))
        else:
            self.store.hset(self.p_path, attr_name, json.dumps(value))

    def _get_from_redis(self, r_serv):
        return r_serv.hgetall(self.p_hash)

    def _get_top_words(self, sort=False):
        """
        Tokenising method: Returning a sorted list or a set of paste's words

        :param sort: Selecting the output: sorted list or a set. (set by default)

        :return: set or sorted list of tuple [(word, occurency)...]

        :Example: PST._get_top_words(False)

        """
        words = {}
        tokenizer = RegexpTokenizer(
            '[\&\~\:\;\,\.\(\)\{\}\|\[\]\\\\/\-/\=\'\"\%\$\?\@\+\#\_\^\<\>\!\*\n\r\t\s]+',
            gaps=True,
            discard_empty=True)

        blob = TextBlob(clean(self.get_p_content()), tokenizer=tokenizer)

        for word in blob.tokens:
            if word in words.keys():
                num = words[word]
            else:
                num = 0
            words[word] = num + 1
        if sort:
            var = sorted(words.iteritems(),
                         key=operator.itemgetter(1),
                         reverse=True)
        else:
            var = words

        return var

    def _get_word(self, word):
        """
        Returning a specific word and his occurence if present in the paste

        :param word: (str) The word

        :return: (tuple) ("foo", 1337)

        """
        return [item for item in self._get_top_words() if item[0] == word]

    def get_regex(self, regex):
        """
        Returning matches with the regex given as an argument.

        :param regex: -- (str) a regex

        :return: (list)

        :Example: PST.get_regex("4[0-9]{12}(?:[0-9]{3})?")


        """
        matchs = []
        for match in re.findall(regex, self.get_p_content()):
            if match != '' and len(match) < 100:
                matchs.append(match)
        return matchs
Пример #18
0
 def signup(self, instance):
     if not (self.ut.text.isdigit()
             and len(self.ut.text) == 7):  #checks validity of student ID
         self.fail.text = 'Invalid Student ID'
         self.ut.text = ''
         self.ut.focus = True
     elif self.ut.text in getUsers(
     ):  #checks if student ID is already in system
         self.fail.text = 'Student ID already in use, please choose another'
         self.ut.text = ''
         self.ut.focus = True
     elif self.pt.text != self.cpt.text:  #checks for matching passwords
         self.fail.text = 'Passwords do not match'
         self.pt.text = ''
         self.cpt.text = ''
         self.pt.focus = True
     elif not (self.ct.text.isdigit()
               and len(self.ct.text) == 8):  #checks validity of hp number
         self.fail.text = 'Invalid Handphone Number'
         self.ct.focus = True
     elif self.ct.text == '':  #checks for empty fields
         self.fail.text = 'Please key in your Handphone Number\nso we can contact you for laundry collection'
         self.ct.focus = True
     elif self.ut.text == '':
         self.fail.text = 'Please key in your User ID'
         self.ut.focus = True
     elif self.pt.text == '':
         self.fail.text = 'Please key in your password'
         self.pt.focus = True
     else:
         createUser(self.ut.text, Hash(self.pt.text),
                    int(self.ct.text))  #creates the user on firebase
         timing, studentid = getState(globalMachine, ['state', 'studentid'])
         weight = [globalWeight]
         machineid = [globalMachine]
         if timing == 0:
             endtime = [time() + washTime + timeOut]
         else:
             endtime = [timing + washTime + timeOut]
         if studentid == None:
             studentid = [self.ut.text]
         else:
             studentid += [self.ut.text]
         putData(self.ut.text,
                 weight=weight,
                 machineid=machineid,
                 endtime=endtime,
                 debt=globalCost)
         if globalState == -1:
             putState(globalMachine,
                      door=1,
                      state=-1,
                      weight=globalWeight,
                      studentid=studentid)
         elif getState(globalMachine, 'state') == 0:
             putState(globalMachine,
                      door=1,
                      state=time(),
                      weight=globalWeight,
                      studentid=studentid)
         else:
             putState(globalMachine,
                      door=1,
                      weight=globalWeight,
                      studentid=studentid)
         self.manager.current = 'contactbot'
Пример #19
0
 def login(self, instance):
     if verify(self.ut.text, Hash(self.pt.text)):
         weight, machineid, endtime = getData(
             self.ut.text, ['weight', 'machineid', 'endtime'])
         if weight == None:  #if wash info is empty
             global globalState
             globalState = 'You do not have any laundry to collect'
             self.manager.current = 'nocollect'
             return None
         else:
             machinels = []
             for machine in range(len(machineid)):
                 if getState(machineid[machine], 'state') == -2:
                     machinels.append(machine)
             if machinels == []:  #if none of the washing machines the user has laundry in is ready
                 global globalState
                 globalState = 'Your laundry is not ready for collection'
                 self.manager.current = 'nocollect'
                 return None
             weightls = []
             machineidls = []
             for machine in sorted(
                     machinels, reverse=True
             ):  #removed ready wash data and puts it into new lists
                 weightls.append(weight.pop(machine))
                 machineidls.append(machineid.pop(machine))
                 endtime.pop(machine)
             putData(self.ut.text,
                     machineid=machineid,
                     weight=weight,
                     endtime=endtime
                     )  #returns not ready wash data back to firebase
             for machine in range(
                     len(machineidls)
             ):  #uses ready wash data to update washing machine status
                 studentid = getState(machineidls[machine], 'studentid')
                 try:
                     studentid.remove(self.ut.text)
                 except ValueError:
                     pass
                 if getState(machineidls[machine],
                             'weight') - weightls[machine] < 0.001:
                     putState(machineidls[machine],
                              door=1,
                              state=0,
                              weight=-weightls[machine],
                              studentid=studentid)
                 else:
                     putState(machineidls[machine],
                              door=1,
                              weight=-weightls[machine],
                              studentid=studentid)
             global globalMachine
             globalMachine = list(
                 set(machineidls)
             )  #puts list of washing machines with user's laundry ready for collection
             self.manager.current = 'collect'
     else:
         self.ut.text = ''
         self.pt.text = ''
         self.fail.text = 'Incorrect User ID or Password'
Пример #20
0
class UserDB:
    def __init__(self):
        self.list = Hash(USER_HASH_SIZE)
        self.followRank = []
        self.tweetRank = []
        self.totalUser = 0

    def addUser(self, id, n):
        if self.list.add(id, n):   # If successfully added
            self.totalUser += 1
            return 1
        else:
            return None

    def deleteUser(self, id):
        if self.list.delete(id):   # If successfully deleted
            self.totalUser -= 1
        else:
            return None

    def getUser(self, id):
        u = self.list.search(id)
        if u:
            return u
        else:
            return None

    def plusFollow(self, id):
        u = self.list.search(id)
        if u:
            u.followCount += 1

    def plusTweet(self, id):
        u = self.list.search(id)
        if u:
            u.tweetCount += 1
            # In construction : need to update leaderboard

    def updateFollowRank(self):
        self.followRank.clear()
        for x in range(len(self.list.hTable)):  # Through Hash List
            n = self.list.hTable[x].start
            while n:                            # Through Linked List
                if n.v:
                    self.followRank.append(n.v)
                n = n.next
        self.followRank = sorted(self.followRank, key=self.getFollow, reverse=True) # Sort by FollowCount
        return self.followRank

    def updateTweetRank(self):
        self.tweetRank.clear()
        for x in range(len(self.list.hTable)):  # Through Hash List
            n = self.list.hTable[x].start
            while n:                            # Through Linked List
                if n.v:
                    self.tweetRank.append(n.v)
                n = n.next
        self.tweetRank = sorted(self.tweetRank, key=self.getTweet, reverse=True)   # Sort by TweetCount
        return self.tweetRank

    def getFollow(self, user):
        return user.followCount

    def getTweet(self, user):
        return user.tweetCount
Пример #21
0
 def __init__(self):
     self.list = Hash(USER_HASH_SIZE)
     self.followRank = []
     self.tweetRank = []
     self.totalUser = 0
Пример #22
0
# Alexandra Veney
import csv
from datetime import time, datetime
from Hash import Hash
from Helper import Helper
from Truck import Truck

NUM_OF_PACKAGES = 40

route_started = False

packages = Hash(NUM_OF_PACKAGES)  # hash object to store packages

packages.create_package_list(
    "Package File.csv")  # create package list from package file

# Big O Notation -> Linear O(N)
with open("Distance Table.csv") as d_file:
    """
    Read in delivery addresses and travel distances from csv files ('Package File' and 'Distance Table')

        Utilizes csv class to read first line from Distance Table which contains the addresses
        Address and location code info stored in dict {location code:street address)
        Distance info stored in tuple  (location, row of distances)
    """
    reader = csv.reader(d_file, delimiter=',')

    # holds row of addresses from file
    addresses = next(reader)

    # get street addresses
Пример #23
0
 def initHash(self):
     new_window = Hash.HashApp(self)
     new_window.show()