Пример #1
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'
Пример #2
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)
Пример #3
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[hashkind] = (Hash(hashkind))
Пример #4
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'))
Пример #5
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()
Пример #6
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)  
Пример #7
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()
Пример #8
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
Пример #9
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
Пример #10
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
Пример #11
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,
Пример #12
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:
Пример #13
0
 def __init__(self):
     self.list = Lista_s()
     self.abb = Arbol_b()
     self.avl = Avl_Tree()
     self.hash = Hash(100)
Пример #14
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'
Пример #15
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")
Пример #16
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'
Пример #17
0
from Hash import Hash

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

print(s.hashFunct('pork'))
s.insert('Steve', 24601)
print(s.list)