Exemplo n.º 1
0
    def politicaClock(self, file):
        pageFaults = 0
        clockHand = 0
        location = []
        hashTable = HashTable(self.M)
        totalLineas = 0
        i = 0
        while i < self.N:
            location.append(PageTableEntry())
            i += 1

        for line in file:
            totalLineas += 1
            line = line.rstrip('\n')
            if location[clockHand].getValidBit() == 1:
                sMH = StringMH(line)
                value = hashTable.getValue(sMH)
                if value is None:
                    pageFaults = pageFaults + 1
                    while location[clockHand].getRefBit() == 1:
                        location[clockHand].setRefBit(0)
                        clockHand = clockHand + 1
                        clockHand = clockHand % self.N
                    key = location[clockHand].getStringMH()
                    hashTable.deleteKey(key)
                    hashTable.putKeyValue(sMH, clockHand)
                    location[clockHand].setStringMH(sMH)
                    location[clockHand].setRefBit(0)
                    clockHand = clockHand + 1
                    clockHand = clockHand % self.N
                else:
                    if location[value].getRefBit() == 1:
                        location[value].setRefBit(0)
                    else:
                        location[value].setRefBit(1)
            else:
                sMH = StringMH(line)
                value = hashTable.getValue(sMH)
                if value is None:
                    pageFaults = pageFaults + 1
                    hashTable.putKeyValue(sMH, clockHand)
                    location[clockHand].setStringMH(sMH)
                    location[clockHand].setValidBit(1)
                    location[clockHand].setRefBit(0)
                    clockHand = clockHand + 1
                    clockHand = clockHand % self.N
                else:
                    if location[value].getRefBit() == 1:
                        location[value].setRefBit(0)
                    else:
                        location[value].setRefBit(1)
        missRate = 100 * (float(pageFaults) / totalLineas)
        missWarm = 100 * (float(pageFaults - self.N) / (totalLineas - self.N))
        mW = pageFaults - self.N
        print "Evaluando una cache CLOCK con " + str(self.N) + " entradas"
        print "Resultados:"
        print "Miss rate:               %0.2f" % missRate + "%%  (%d" % pageFaults + " misses out of %d" % totalLineas + " references)"
        print "Miss rate (warm cache):  %0.2f" % missWarm + "%%  (%d" % mW + " misses out of %d" % totalLineas + "-%d" % self.N + " references)"
Exemplo n.º 2
0
def main():
    hash_table = HashTable()

    for x in range(20):
        hash_table.insert(x, str(x))

    for x in hash_table.getHashTable():
        print(len(x))
        print(*x)
Exemplo n.º 3
0
    def politicaClock(self, file):
        pageFaults = 0
        clockHand = 0
        location = []
        hashTable = HashTable(self.M)
        totalLineas = 0
        i = 0
        while i < self.N:
            location.append(PageTableEntry())
            i += 1

        for line in file:
            totalLineas += 1
            line = line.rstrip('\n')
            if location[clockHand].getValidBit() == 1:
                sMH = StringMH(line)
                value = hashTable.getValue(sMH)
                if value is None:
                    pageFaults = pageFaults + 1
                    while location[clockHand].getRefBit() == 1:
                        location[clockHand].setRefBit(0)
                        clockHand = clockHand + 1
                        clockHand = clockHand % self.N
                    key = location[clockHand].getStringMH()
                    hashTable.deleteKey(key)
                    hashTable.putKeyValue(sMH,clockHand)
                    location[clockHand].setStringMH(sMH)
                    location[clockHand].setRefBit(0)
                    clockHand = clockHand + 1
                    clockHand = clockHand % self.N
                else:
                    if location[value].getRefBit() == 1:
                        location[value].setRefBit(0)
                    else:
                        location[value].setRefBit(1)
            else:
                sMH = StringMH(line)
                value = hashTable.getValue(sMH)
                if value is None:
                    pageFaults =  pageFaults + 1
                    hashTable.putKeyValue(sMH,clockHand)
                    location[clockHand].setStringMH(sMH)
                    location[clockHand].setValidBit(1)
                    location[clockHand].setRefBit(0)
                    clockHand = clockHand + 1
                    clockHand = clockHand % self.N
                else:
                    if location[value].getRefBit() == 1:
                        location[value].setRefBit(0)
                    else:
                        location[value].setRefBit(1)
        missRate = 100*(float(pageFaults)/totalLineas)
        missWarm = 100*(float(pageFaults - self.N)/(totalLineas-self.N))
        mW = pageFaults - self.N
        print "Evaluando una cache CLOCK con " + str(self.N) + " entradas"
        print "Resultados:"
        print "Miss rate:               %0.2f" %missRate + "%%  (%d" %pageFaults + " misses out of %d" %totalLineas + " references)"
        print "Miss rate (warm cache):  %0.2f" %missWarm + "%%  (%d" %mW + " misses out of %d" %totalLineas + "-%d" %self.N + " references)"
Exemplo n.º 4
0
def main():
    my_dict = HashTable()
    file = open('ispell.dict', 'r')
    for word in file:
        my_dict.insert((word[:-1], ))
    file.close()
    word = input('Enter word : ').split()[0]
    for i in range(len(word)):
        for ch in range(ord('a'), ord('z')):
            if chr(ch) == word[i]:
                continue
            new = word[:i] + chr(ch) + word[i + 1:]
            if my_dict.search(new) is not None:
                print(new)
Exemplo n.º 5
0
def depth_first_search__scan(sm, h):
    MAXNODES = 20000000
    openSet = [sm]
    ht = HashTable.HashTable()
    ht.checkAdd(sm)
    nodes = 0

    while len(openSet) > 0:
        currentState = openSet.pop()
        #currentState.printMap()

        nodes += 1
        if currentState.isSolution():
            return currentState  # SOLUTION FOUND!!!

        if nodes % 1000 == 0:
            print(nodes, " nodes checked")
            sys.stdout.flush()
        if nodes == MAXNODES:
            print("Limit of nodes reached: exiting without a solution.")
            sys.exit(1)

        for x in currentState.children():
            # check if this has already been generated
            if ht.checkAdd(x):
                continue

            openSet.append(x)
    return None
Exemplo n.º 6
0
def seeds(dict, i, k, ht):
    seedArray = []
    for j in range(len(dict[i]) - k):
        hash_subseq = HashTable.hash_djb2(dict[i][j:j + k])
        if hash_subseq in ht:
            if j not in seedArray:
                seedArray.append((j, hash_subseq))
    dist = []
    if len(seedArray) > 3:
        for z in range(len(seedArray) - 1):
            dist.append(seedArray[z + 1][0] - seedArray[z][0])
        re = []
        for z in range(len(dist)):
            if dist[z] <= 50:
                if seedArray[z] in re:
                    re.append(seedArray[z + 1])
                else:
                    re.append(seedArray[z])
                    re.append(seedArray[z + 1])
        if len(re) >= 3:
            return re
        else:
            return None
    else:
        return None
Exemplo n.º 7
0
    def __init__(self, size, init_list=None, skip=1):
        """
        Initializes the dictionary.
        """
        self.size = size
        self.skip = skip
        self.n_items = 0

        # Init hash table (keys) and data table (values)
        self.keys = HashTable(size, collision='rehashing', param=skip)
        self.values = [None] * self.size

        # Add the initial list of (key, value) to the dictionary
        if (init_list is not None):
            for key, value in init_list:
                self.put(key, value)
Exemplo n.º 8
0
    def hashJoin(self, tabela1, tabela2):

        resultado = []

        hashing = HashTable(len(tabela1))

        file = open("t/hash.txt", "w")

        for s in tabela2:
            linha = s.split("\t")
            hashing.insereHash(s)
        for i in tabela1:
            linha = i.split("\t")
            resultado = hashing.procuraHash(linha[1])
            if resultado is not None:
                file.write(resultado + "\t" + "\t".join(linha) + "\n")
Exemplo n.º 9
0
def CreateSprite(image):
    # send function 2 to the server [2:4][imageID:4]
    FTSMain.SEND(struct.pack("ii", 2, image))
    reply = FTSMain.RECEIVE("i", 4)
    spr = SPRITE(reply[0], image)
    HashTable.HTInsert(FTSMain.SPRITETABLE, SPRITEHASHFUNCTION, spr)
    return reply[0]
Exemplo n.º 10
0
def Sparkseeds(dict, i, k, hashDF, sc):
    word = [(i, HashTable.hash_djb2(dict[i][j:j + k]), j)
            for j in range(0,
                           len(dict[i]) - k)]
    rddW = sc.parallelize(word)
    schemaWordDF = rddW.map(
        lambda x: Row(NUM_SEQ=x[0], ID_SEQ=x[1], POS_SEQ=x[2]))
    df = sqlContext.createDataFrame(schemaWordDF)
    reDF = df.join(hashDF, df.ID_SEQ == hashDF.ID_GEN, how='inner')
    reDF = reDF.orderBy(reDF.POS_SEQ).select(reDF.NUM_SEQ, reDF.ID_SEQ,
                                             reDF.POS_SEQ, reDF.POS_GEN)
    my_window = Window.partitionBy(reDF.NUM_SEQ).orderBy(reDF.POS_SEQ)
    reDF = reDF.withColumn("prev_value", F.lag(reDF.POS_SEQ).over(my_window))
    reDF = reDF.withColumn(
        "dist",
        F.when(F.isnull(reDF.POS_SEQ - reDF.prev_value),
               0).otherwise(reDF.POS_SEQ - reDF.prev_value))
    reDF = reDF.select(reDF.NUM_SEQ, reDF.ID_SEQ, reDF.POS_SEQ, reDF.dist,
                       reDF.POS_GEN)
    reDF = reDF.withColumn("dist0", F.lead(reDF.dist).over(my_window))
    elDF = reDF.filter(((reDF.dist == 0) | (reDF.dist >= 50))
                       & ((reDF.dist0.isNull()) | (reDF.dist0 >= 50)))
    reDF = reDF.subtract(elDF)
    reDF = reDF.orderBy(reDF.POS_SEQ).select(reDF.NUM_SEQ, reDF.ID_SEQ,
                                             reDF.POS_SEQ, reDF.POS_GEN)

    #pos = function(reDF)

    return reDF
Exemplo n.º 11
0
def LoadImageSliced(filename, sx, sy):
    # a byte array of the filename
    ar = bytearray(map((lambda x: ord(x)), list(filename)))
    # make it 256 bytes in length (must be fixed size!)
    for i in range(0, (256 - len(filename))):
        ar += bytearray([0])
    # send function 1 to server [1:4][filename:256][sx:4][sy:4]
    FTSMain.SEND(struct.pack("i", 1) + ar + struct.pack("ii", sx, sy))
    reply = FTSMain.RECEIVE("iii", 12)  # get a response [ID,width,height]
    img = IMAGE(reply[0], reply[1], reply[2])
    HashTable.HTInsert(FTSMain.IMAGETABLE, IMAGEHASHFUNCTION, img)
    return reply[0]  # return the ID
Exemplo n.º 12
0
    def __init__(self, name, capacity=0, force_init=False, serializer=marshal):
        """
        'name'          the path of the file to be 'mmap'ed
                        use MemCacher(name, ...) to add prefix '/dev/shm' automatically
        'capacity'      optional, if you want to connect to an existing shmht
        'serializer'    should contain loads/dumps (marshal, json, pickle, etc.)
        """

        self.ht = HashTable.HashTable(name, capacity, force_init, serializer)
        self.d = {}
        self.loads = serializer.loads
        self.dumps = serializer.dumps
    def __init__(self, timeout, receiving_port):
        # self.udp_ip = udp_ip
        # self.udp_port = udp_port
        # self.message = message
        # self.local_port = local_port
        self.udp_obj = udpSendRecieve.UDPNetwork(receiving_port)
        self.timeout = timeout

        self.cache = HashTable.HashTable("ServerCache")
        self.cache.clean()
        # self.stack = Stack()
        self.list = []
Exemplo n.º 14
0
	def __init__(self, port, maxnodes, replicate_factor = 0):
		self._comm = Comm(port)
		self._nodeid = int(hashlib.sha1(self._comm.getIpPort().encode()).hexdigest(), 16) % maxnodes
		self._message_creator = Messages(self._comm.ip, port, self._nodeid)
		self._finger_table = FingerTable(self._nodeid, maxnodes)
		self._hash_table = HashTable()
		self._replicate_factor = replicate_factor
		self._message_handler = {
			"get": self.getKey,
			"retrieve": self.retrieveKey,
			"put": self.putKey,
			"del": self.delKey,
			"join": self.join,
			"join_response": self.joinResponse,
			"table_update": self.updateTable,
			"table_response": self.updateTableResponse,
			"route": self.routeMessage,
			"error": self._infoPrinter,
			"response": self._infoPrinter
		}
		self._hash_table.putNodeInfo(self._nodeid, self._comm.ip, self._comm.port)
Exemplo n.º 15
0
def main():
    dict = input("Enter the dictionary filename: ")  # ex: words.txt
    grd = input("Enter the grid filename: ")  # ex: 4x7.grid.txt
    args = [dict, grd]
    global grid
    grid, rows, cols = readInGrid(
        args[1])  # reads the grid file into the variable 'grid'
    global switch
    switch = create_switch()
    global r, c
    r, c = 0, 0

    dict1 = open(args[0])
    size = 0
    for _ in dict1:
        size += 1  # size is the number of words in the dictionary
    dict1.close()

    hashTable = HashTable.HashTable(size, 0.2)
    hashTable = readInDict(
        args[0], hashTable
    )  # creates the Hash Table and inserts the words from the dictionary file into it.
    count = 0
    prevWord = ""
    timer = time.time()  # 'start' the timer
    longestWord = 25
    outputFile = open("out.txt", "w")
    for r1 in range(rows):
        for c1 in range(cols):
            for d in range(8):
                for l in range(
                        3, longestWord
                ):  # These loops iterate through each position, then in each direction and length.
                    word = getWordInGrid(r1, c1, d, l, rows, cols)

                    if word == prevWord:  # Ensures that the same word is not searched multiple times when the end of the grid is reached
                        continue
                    prevWord = word
                    test = hashTable.find(word)

                    if test:  # Writes the found words to the file
                        outputFile.write(switch[d].__name__ + " (" + str(r1) +
                                         ", " + str(c1) + "):    " + word +
                                         "\n")
                        count += 1
    timer = time.time() - timer
    outputFile.close()
    print(str(count) + " words found")
    print("Found all words in " + str(timer) + " seconds")
    return 0
Exemplo n.º 16
0
 def test_insert(self):
     '''
     Test Hash Table class for setting, getting and itteration
     :return:
     '''
     self.my_hash = HashTable(10)
     self.my_hash.set('ali', 100)
     self.my_hash.set('kadir', 200)
     self.my_hash.set('halil', 300)
     self.my_hash.set('hayri', 400)
     self.my_hash.set('cevdet', 500)
     self.my_hash.set('celal', 600)
     # Test for values
     self.assertEqual(100, self.my_hash.get('ali'))
     self.assertEqual(200, self.my_hash.get('kadir'))
     self.assertEqual(300, self.my_hash.get('halil'))
     self.assertEqual(400, self.my_hash.get('hayri'))
     self.assertEqual(500, self.my_hash.get('cevdet'))
     self.assertEqual(600, self.my_hash.get('celal'))
     # Test for keys
     self.assertEqual('ali', self.my_hash.index(100))
     self.assertEqual('kadir', self.my_hash.index(200))
     self.assertEqual('halil', self.my_hash.index(300))
     self.assertEqual('hayri', self.my_hash.index(400))
     self.assertEqual('cevdet', self.my_hash.index(500))
     self.assertEqual('celal', self.my_hash.index(600))
     # Test for iteration
     self.new_hash = HashTable(3)
     self.new_hash.set('a', 1)
     self.new_hash.set('b', 2)
     self.new_hash.set('c', 3)
     iterable = iter(self.new_hash)
     self.assertEqual(next(iterable), 3)
     self.assertEqual(next(iterable), 1)
     self.assertEqual(next(iterable), 2)
     self.assertRaises(StopIteration, next, iterable)
Exemplo n.º 17
0
def GetNTsHashTable(gen, nt_list):
    hashtable_lst = []
    for nt in nt_list:
        if isinstance(nt, str):
            nt_name = nt
        else:
            nt_name = nt.name
        all_context = gen.DFSNTContext([nt], nt)
        if len(all_context) == 0:
            continue
        if "_BIND" in nt_name or "_EMIT" in nt_name:
            nt_name = nt_name[:-5]
        hashtable = HashTable.HashTable(nt_name)
        hashtable.LoadContext(all_context)
        hashtable_lst.append(hashtable)
    return hashtable_lst
import csv
import HashTable
from Delivery import Truck, Package, Location, allPackages, loadedPackages

packageTable = HashTable.PackageHashTable()
allLocations = []
allDistances = []
allAddresses = []
totalMilesTraveled = 0.0

# Opens the WGUPS Addresses file, creates a Location for each address
# Runs in O(N)
with open("WGUPS Addresses.csv", "r") as addressFile:
    csv_reader = csv.reader(addressFile)
    for line in csv_reader:
        allAddresses.append(line)
        locationID = line[0]
        name = line[1]
        address = line[2]
        location = Location(locationID, name, address)
        allLocations.append(location)

# Opens WGUPS Distance Table file, adds the appropriate Distance array to each previously created Location
# Runs in O(N)
with open("WGUPS Distance Table.csv", "r") as distanceFile:
    csv_reader = csv.reader(distanceFile)
    for line in csv_reader:
        allDistances.append(line)
    for location in allLocations:
        locID = int(location.locationID)
        location.updateDistanceArray(allDistances[locID])
Exemplo n.º 19
0
 def test_insert(self):
     hash_table = HashTable()
     hash_table.insert(1, str(1))
     self.assertEqual(len(hash_table.getHashTable()), 20)
Exemplo n.º 20
0
 def __init__(self, size):
     assert (size > 0)
     self.table = HashTable.HashTable(size)
Exemplo n.º 21
0
import HashTable as ht
import UnionFindSet as ufs
import sys

accounts = [["David", "*****@*****.**", "*****@*****.**", "*****@*****.**"],
            ["David", "*****@*****.**", "*****@*****.**", "*****@*****.**"],
            ["David", "*****@*****.**", "*****@*****.**", "*****@*****.**"],
            ["David", "*****@*****.**", "*****@*****.**", "*****@*****.**"],
            ["David", "*****@*****.**", "*****@*****.**", "*****@*****.**"]]

#accounts = [["John","*****@*****.**","*****@*****.**"],["John","*****@*****.**","*****@*****.**"],["Mary","*****@*****.**"],["John","*****@*****.**"]]

hashtable_size = len(accounts) * 30
table = ht.HashTable(hashtable_size)
user_dict = []

for i, v in enumerate(accounts):
    user_dict.append(v[0])
    accounts[i][0] = i
    for e_idx in range(1, len(v)):
        hash_index = hash(v[e_idx]) % ((sys.maxsize + 1) * 2)
        table.put(hash_index, v[e_idx])
        accounts[i][e_idx] = hash_index

uts_table = ufs.UnionFindSet(range(len(user_dict)))
for v in accounts:
    for idx in range(1, len(v)):
        uts_table.union(v[idx - 1], v[idx])

#print(table.hashtable)
print(uts_table.father_dict)
Exemplo n.º 22
0
"""map a timenode to the correct node in the OD list of timeNodes"""
"""PersonA took PathB at TimeC from OriginD to DestinationE"""

timeTolerance = 30
"""the variables that PersonA used"""
OriginD = Coordinate.Coordinate(40, -78)
DestinationE = Coordinate.Coordinate(50, -80)

timeCString = "08:00"
timeCDate = datetime.strptime(timeCString, "%H:%M")
TimeC = TimeNode.TimeNode(timeCDate, timeTolerance)

pathB = "66W"
"""process to capture event"""
"""create a hashTable"""
ODNodes = HashTable.HashTable(1)
odNode = ODNode.ODNode(Coordinate.Coordinate(40.5, -78),
                       Coordinate.Coordinate(50.5, -80), 0)
ODNodes.insert(odNode)
"""create a list of times to be looked at"""
odNode.createTimeIntervals("06:00", "10:00", timeTolerance)

# print("initial Node with Times Added")
# print(odNode.toString())
"""see if PersonA's origin and destination can be mapped"""
tempNode = ODNode.ODNode(OriginD, DestinationE, 0)

if ODNodes.__contains__(tempNode, 100, 100):
    """find and increment the correct node"""
    n = ODNodes.find(tempNode, 100, 100)
    """increment the count on this node"""
Exemplo n.º 23
0
            f.write('%d: %f, %f, %f\n' %
                    (k, best_test[0][k], best_test[1][k], best_test[2][k]))
    print("Tran C done.")
    sampler.close()
else:
    print tf.train.latest_checkpoint(C_logdir)
    saver.restore(sess, tf.train.latest_checkpoint(C_logdir))
    best_P, best_Q = sess.run([model.P, model.Q])
sess.close()
tf.reset_default_graph()

# building candidates
[P, Q] = best_P, best_Q
P = (np.sign(P) + 1) / 2
Q = (np.sign(Q) + 1) / 2
H = HashTable(Q, m=args.F_m, r=args.hash_r)
print 'Getting candidates...'
t0 = time.time()
candidates = defaultdict(list)
sampled_users = random.sample(xrange(usernum), 10000)
if args.F_hr > 0.0:
    try:
        [candidates] = np.load(C_logdir + '/cache.npy')
    except:
        candidates = [None for _ in range(usernum)]
        for u in tqdm(xrange(usernum),
                      total=usernum,
                      ncols=70,
                      leave=False,
                      unit='users'):
            # for u in range(args.usernum):
Exemplo n.º 24
0
class MyWin(QMainWindow, Ui_MainWindow):
    start_add_time, end_add_time = None, None
    start_delete_key_time, end_delete_key_time = None, None
    start_delete_value_time, end_delete_value_time = None, None
    start_search_key_time, end_search_key_time = None, None
    start_search_value_time, end_search_value_time = None, None

    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.hash_table = None

        self.initialize_windows()
        self.work_with_menu()

    def handle_input_add(self, key, val1, val2, val3):
        if self.hash_table:
            self.start_add_time = time.time()
            self.hash_table.add(key, val1, val2, val3)
            self.end_add_time = time.time()

    def handle_input_change(self, key, val1, val2, val3):
        if self.hash_table:
            self.hash_table.change(key, val1, val2, val3)

    def handle_input_delete_key(self, key):
        if self.hash_table:
            self.start_delete_key_time = time.time()
            self.hash_table.delitem(key)
            self.end_delete_key_time = time.time()

    def handle_input_delete_value(self, tf1, tf2, tf3, val):
        if self.hash_table:
            if tf1 and not tf2 and not tf3:
                self.start_delete_value_time = time.time()
                self.hash_table.delitem_value(val, None, None)
                self.end_delete_value_time = time.time()
            elif not tf1 and tf2 and not tf3:
                self.start_delete_value_time = time.time()
                self.hash_table.delitem_value(None, val, None)
                self.end_delete_value_time = time.time()
            elif not tf1 and not tf2 and tf3:
                self.start_delete_value_time = time.time()
                self.hash_table.delitem_value(None, None, val)
                self.end_delete_value_time = time.time()
            else:
                pass

    def handle_input_search(self):
        if self.hash_table:
            if self.idEdit.text() and self.serialNameEdit.text() == '' and self.numSeriesEdit.text() == ''\
                    and self.isWatchedEdit.text() == '':
                self.start_search_key_time = time.time()
                self.hash_table.getitem(self.idEdit.text())
                self.end_search_key_time = time.time()
            else:
                if self.serialNameEdit.text() and self.numSeriesEdit.text(
                ) == '' and self.isWatchedEdit.text() == '':
                    self.start_search_value_time = time.time()
                    self.hash_table.getitem_value(self.serialNameEdit.text(),
                                                  None, None)
                    self.end_search_value_time = time.time()
                elif self.serialNameEdit.text(
                ) == '' and self.numSeriesEdit.text(
                ) and self.isWatchedEdit.text() == '':
                    self.start_search_value_time = time.time()
                    self.hash_table.getitem_value(None,
                                                  self.numSeriesEdit.text(),
                                                  None)
                    self.end_search_value_time = time.time()
                elif self.serialNameEdit.text(
                ) == '' and self.numSeriesEdit.text(
                ) == '' and self.isWatchedEdit.text():
                    self.start_search_value_time = time.time()
                    self.hash_table.getitem_value(None, None,
                                                  self.isWatchedEdit.text())
                    self.end_search_value_time = time.time()
                else:
                    pass

    def initialize_windows(self):
        self.add_w = AddRecordWin()
        self.add_w.adding_data.connect(self.handle_input_add)
        self.add_w.okButton.clicked.connect(self.send_data_add_w)
        self.add_w.cancelButton.clicked.connect(self.close)

        self.change_w = ChangeRecordWin()
        self.change_w.changing_data.connect(self.handle_input_change)
        self.change_w.okButton.clicked.connect(self.send_data_change_w)
        self.change_w.cancelButton.clicked.connect(self.close)

        self.delete_k_w = DeleteByKeyWin()
        self.delete_k_w.deleting_key_data.connect(self.handle_input_delete_key)
        self.delete_k_w.okButton.clicked.connect(self.send_data_delete_k_w)
        self.delete_k_w.cancelButton.clicked.connect(self.close)

        self.delete_v_w = DeleteByValueWin()
        self.delete_v_w.deleting_value_data.connect(
            self.handle_input_delete_value)
        self.delete_v_w.okButton.clicked.connect(self.send_data_delete_v_w)
        self.delete_v_w.cancelButton.clicked.connect(self.close)

        self.searchButton.clicked.connect(self.search_data)

        self.tableWidget.setHorizontalHeaderLabels(
            ['id', 'serial_name', 'number_of_series', 'is_watched'])
        self.tableWidget.setMouseTracking(True)
        self.tableWidget.setFixedSize(545, 271)

        self.showButton.clicked.connect(self.show_hash_table)

    def work_with_menu(self):
        self.actionNew.triggered.connect(self.create_new_hash_table)
        self.actionOpen.triggered.connect(self.open_hash_table)
        self.actionSave.triggered.connect(self.save_hash_table)
        self.actionClean.triggered.connect(self.clean_hash_table)
        self.actionDelete.triggered.connect(self.delete_hash_table)
        self.actionAddRecord.triggered.connect(self.show_AddRecordWin)
        self.actionChangeRecord.triggered.connect(self.show_ChangeRecordWin)
        self.actionDelete_by_key.triggered.connect(self.show_DeleteByKeyWin)
        self.actionDelete_by_value.triggered.connect(
            self.show_DeleteByValueWin)

    def create_new_hash_table(self):
        self.hash_table = HashTable()

    def open_hash_table(self):
        self.create_new_hash_table()
        filename = QFileDialog.getOpenFileName(self, 'Open file', '/data',
                                               "Image files (*.txt)")[0]
        self.hash_table.open_data_base(filename)
        #self.hash_table.str()

    def save_hash_table(self):
        if self.hash_table:
            if self.hash_table.current_size:
                #self.hash_table.str()
                filename = QFileDialog.getSaveFileName(
                    self, 'Open file', '/data', "Image files (*.txt)")[0]
                self.hash_table.save_data_base(filename)

    def clean_hash_table(self):
        if self.hash_table:
            self.hash_table.clean()

    def delete_hash_table(self):
        del self.hash_table

    def show_AddRecordWin(self):
        self.add_w.show()

    def show_ChangeRecordWin(self):
        self.change_w.show()

    def show_DeleteByKeyWin(self):
        self.delete_k_w.show()

    def show_DeleteByValueWin(self):
        self.delete_v_w.show()

    def show_hash_table(self):
        try:
            if self.hash_table:
                if self.tableWidget:
                    self.tableWidget.clear()
                    self.tableWidget.setHorizontalHeaderLabels([
                        'id', 'serial_name', 'number_of_series', 'is_watched'
                    ])
                    self.tableWidget.setRowCount(0)
                records_list = self.hash_table.repr()
                for record in records_list:
                    row_position = self.tableWidget.rowCount()
                    self.tableWidget.insertRow(row_position)
                    for i in range(4):
                        self.tableWidget.setItem(
                            row_position, i,
                            QtWidgets.QTableWidgetItem(str(record[i])))
        except AttributeError:
            pass

    def send_data_add_w(self):
        self.add_w.adding_data.emit(self.add_w.idEdit.text(),
                                    self.add_w.serialNameEdit.text(),
                                    self.add_w.numSeriesEdit.text(),
                                    self.add_w.isWatchedEdit.text())
        '''print("def send_data(self): ",
              self.add_w.idEdit.text(),
              self.add_w.serialNameEdit.text(),
              self.add_w.numSeriesEdit.text(),
              self.add_w.isWatchedEdit.text())  # Пытаюсь посмотреть что лежит в собранных данных, временная мера'''
        self.add_w.hide()

    def send_data_change_w(self):
        self.change_w.changing_data.emit(self.change_w.idEdit.text(),
                                         self.change_w.serialNameEdit.text(),
                                         self.change_w.numSeriesEdit.text(),
                                         self.change_w.isWatchedEdit.text())
        self.change_w.hide()

    def send_data_delete_k_w(self):
        self.delete_k_w.deleting_key_data.emit(self.delete_k_w.idEdit.text())
        self.delete_k_w.hide()

    def send_data_delete_v_w(self):
        self.delete_v_w.deleting_value_data.emit(
            self.delete_v_w.serialNameBox.isChecked(),
            self.delete_v_w.numSeriesBox.isChecked(),
            self.delete_v_w.isWatchedBox.isChecked(),
            self.delete_v_w.valueEdit.text())
        self.delete_v_w.hide()

    def search_data(self):
        try:
            if self.hash_table:
                if self.tableWidget:
                    self.tableWidget.clear()
                    self.tableWidget.setHorizontalHeaderLabels([
                        'id', 'serial_name', 'number_of_series', 'is_watched'
                    ])
                    self.tableWidget.setRowCount(0)
                self.handle_input_search()
                records_list = self.hash_table.repr(
                    path='service_files/result_search.txt')
                for record in records_list:
                    row_position = self.tableWidget.rowCount()
                    self.tableWidget.insertRow(row_position)
                    for i in range(4):
                        self.tableWidget.setItem(
                            row_position, i,
                            QtWidgets.QTableWidgetItem(str(record[i])))
        except AttributeError:
            pass

    def time_statistic(self):
        print('Adding new record: ', self.end_add_time - self.start_add_time)
        print('Deleting by key: ',
              self.end_delete_key_time - self.start_delete_key_time)
        print('Deleting by one value: ',
              self.end_delete_value_time - self.start_delete_value_time)
        print('Searching by key: ',
              self.end_search_key_time - self.start_search_key_time)
        print('Searching by value: ',
              self.end_search_value_time - self.start_search_value_time)

    def closeEvent(self, event):
        reply = QMessageBox.question(self, 'Message', "Are you sure to quit?",
                                     QMessageBox.Yes | QMessageBox.No,
                                     QMessageBox.No)

        if reply == QMessageBox.Yes:
            self.time_statistic()
            event.accept()
        else:
            event.ignore()
Exemplo n.º 25
0
def IDAstar(sm, h):
    MAXNODES = 20000000
    openSet = []
    closedSet = []
    visitSet = []
    pathLimit = h(sm) - 1
    sucess = False
    it = 0

    while True:
        pathLimit = pathLimit + 1
        print("current pathLimit = ", pathLimit)
        sm.setG(0)
        openSet.insert(0, sm)
        ht = HashTable.HashTable()
        nodes = 0

        while len(openSet) > 0:
            currentState = openSet.pop(0)
            #currentState.printMap()

            nodes = nodes + 1
            if currentState.isSolution():
                return currentState  # SOLUTION FOUND!!!

            if nodes % 1000000 == 0:
                print((nodes / 1000000), "M nodes checked")
            if nodes == MAXNODES:
                print("Limit of nodes reached: exiting without a solution.")
                sys.exit(1)

            if currentState.getF() <= pathLimit:
                closedSet.insert(0, currentState)
                # get the sucessors of the current state
                for x in currentState.children():
                    # test if node has been "closed"
                    if isClosed(closedSet, x):
                        continue

                    # check if this has already been generated
                    if ht.checkAdd(x):
                        continue

                    # compute G for each
                    x.setG(currentState.getG() + 1)
                    x.setF(x.getG() + h(x))
                    #x.setParent(currentState)
                    openSet.insert(0, x)  # push
            else:
                visitSet.insert(0, currentState)

        #print "Nodes checked = ", nodes
        print("iteration = ", it)
        it = it + 1
        if len(visitSet) == 0:
            print("FAIL")
            return None

        # set a new cut-off value (pathLimit)
        low = visitSet[0].getF()
        for x in visitSet:
            if x.getF() < low:
                low = x.getF()
        pathLimit = low

        # move nodes from VISIT to OPEN and reset closedSet
        openSet.extend(visitSet)
        visitSet = []
        closedSet = []
Exemplo n.º 26
0
def main():
    ht = HashTable()
    ht.put(23, "ella")
    ht.put(70, "mars")
    ht.put(6, "nocturnal")
    ht.put(1, "moo")
    ht.put(21, "medee")
    ht.put(41, "golden")
    print(ht.get(23))
    print(ht.get(6))
    print(ht.get(1))
    print(ht.get(21))
    print(ht.hasKey(6))
    ht.delete(6)
    print(ht.hasKey(6))
Exemplo n.º 27
0
    def politicaLRU(self, file):
        location = DoubleLinkedList()
        pageFaults = 0
        indice = 0
        llena = False
        hashTable = HashTable(self.M)
        totalLineas = 0

        for line in file:
            totalLineas += 1
            line = line.rstrip('\n')
            if llena:
                sMH = StringMH(line)
                value = hashTable.getValue(sMH)
                if value is None:
                    pageFaults = pageFaults + 1
                    firstNodeData = location.removeFirstNode()
                    hashTable.deleteKey(firstNodeData)
                    refNode = location.append(sMH)
                    hashTable.putKeyValue(sMH, refNode)
                else:
                    location.remove(value)
                    refNode = location.append(sMH)
                    hashTable.updateValue(sMH, refNode)
            else:
                sMH = StringMH(line)
                value = hashTable.getValue(sMH)
                if value is None:
                    pageFaults = pageFaults + 1
                    refNode = location.append(sMH)
                    hashTable.putKeyValue(sMH, refNode)
                    indice = indice + 1
                    if indice >= self.N:
                        llena = True
                else:
                    location.remove(value)
                    refNode = location.append(sMH)
                    hashTable.updateValue(sMH, refNode)

        missRate = 100*(float(pageFaults)/totalLineas)
        missWarm = 100*(float(pageFaults - self.N)/(totalLineas-self.N))
        mW = pageFaults - self.N
        print "Evaluando una cache LRU con " + str(self.N) + " entradas"
        print "Resultados:"
        print "Miss rate:               %0.2f" %missRate + "%%  (%d" %pageFaults + " misses out of %d" %totalLineas + " references)"
        print "Miss rate (warm cache):  %0.2f" %missWarm + "%%  (%d" %mW + " misses out of %d" %totalLineas + "-%d" %self.N + " references)"
Exemplo n.º 28
0
def IDAstar(sokomap, heuristic) -> [(int, int)]:
    MAXNODES = 20000000
    openSet: [sokomap] = []
    closedSet: [sokomap] = []
    visitSet: [sokomap] = []
    pathLimit = heuristic(sokomap) - 1
    it = 0

    sokomap.uniqueBlocksGoals()
    sokomap.buildLowerBoundTable()

    while True:
        pathLimit += 1
        print("current pathLimit = ", pathLimit)
        sokomap.setG(0)
        openSet.insert(0, sokomap)
        ht = HashTable.HashTable()
        nodes = 0

        while len(openSet) > 0:
            currentState = openSet.pop(0)
            if DEV_DEBUG:
                currentState.printMap()
                moveList = currentState.getMoveList()
                print(
                    f'"openSet.pop(0)" movelist={getFormattedMoves(moveList)}')

            if len(currentState.getUnplacedBlocks()) < 1:
                print()

            nodes = nodes + 1
            if currentState.isSolution():
                return currentState  # SOLUTION FOUND!!!

            if nodes % 1000000 == 0:
                print((nodes / 1000000), "M nodes checked")
            if nodes == MAXNODES:
                print("Limit of nodes reached: exiting without a solution.")
                sys.exit(1)

            if currentState.getF() <= pathLimit:
                closedSet.insert(0, currentState)
                # get the sucessors of the current state
                children = currentState.getChildren()
                for child in children:
                    # test if node has been "closed"
                    if isClosed(closedSet, child):
                        continue

                    # check if this has already been generated
                    if ht.checkAdd(child):
                        if DEV_DEBUG:
                            print(f'We have already gone this way.')
                        continue

                    # compute G for each
                    child.setG(currentState.getG() + 1)
                    child.setF(child.getG() + heuristic(child))
                    #x.setParent(currentState)

                    if DEV_DEBUG:
                        print(f'Moving.')
                    openSet.insert(0, child)  # push
            else:
                visitSet.insert(0, currentState)

        #print "Nodes checked = ", nodes
        print("iteration = ", it)
        it = it + 1
        if len(visitSet) == 0:
            print("FAIL")
            return None

        # set a new cut-off value (pathLimit)
        low = visitSet[0].getF()
        for child in visitSet:
            if child.getF() < low:
                low = child.getF()
        pathLimit = low

        # move nodes from VISIT to OPEN and reset closedSet
        openSet.extend(visitSet)
        visitSet = []
        closedSet = []
Exemplo n.º 29
0
class Scanner:
    __sursa = ""
    __string = ""
    __list = []
    __cod_atom = []
    __cod_ts = []
    __ts = HashTable.HashTable()
    __i = 0
    __numbersAF = AF("intregi.txt")
    __identifierAF = AF("gucci.txt")

    def __init__(self, sursa) -> None:
        super().__init__()
        self.__sursa = sursa

    """
    Citeste fisierul sursa si il salveaza intr-ul string
    """

    def read(self):
        with open(self.__sursa, 'r') as reader:
            self.__string = reader.read()

    """
    Ia urmatorul caracter din string
    """

    def get(self):
        aux = self.__string[self.__i]
        self.__i += 1
        return aux

    """
    Ia caracterul anterior
    """

    def back(self):
        self.__i -= 1

    """
    Creeaza tabelul FIP
    """

    def make_fip(self):
        self.__cod_atom = [-1] * len(self.__list)
        self.__cod_ts = [-1] * len(self.__list)
        x = 0
        for i in self.__list:
            if i in config:
                self.__cod_atom[x] = config.index(i)
                self.__cod_ts[x] = -1
            elif self.__identifierAF.wrapper_verifica(i):  # is ID
                if len(i) < 8:
                    self.__cod_atom[x] = 1
                    val = sum([ord(j) for j in i])
                    aux = self.__ts.cauta(val)
                    if not aux:
                        self.__ts.adauga(val)
                    self.__cod_ts[x] = self.__ts.index(val) + 1
            elif self.__numbersAF.wrapper_verifica(i):  # is constant
                self.__cod_atom[x] = 2
                val = sum([ord(j) for j in i])
                aux = self.__ts.cauta(val)
                if not aux:
                    self.__ts.adauga(val)
                self.__cod_ts[x] = self.__ts.index(val) + 1
            else:
                print(i)
                raise Exception("SYNTAX IS WRONG")
            x += 1

    """
    Pune tokenuri in lista
    """

    def parser(self):
        temporary_string = ""
        while True:
            try:
                aux = self.get()
                if aux in string.ascii_letters or aux in string.digits or aux in [
                        '$', '_', '.'
                ]:
                    temporary_string += aux
                elif aux in ['+', '-']:
                    if temporary_string == "":
                        temporary_string += aux
                    else:
                        self.__list.append(temporary_string)
                        temporary_string = ""
                        aux2 = self.get()
                        if aux + aux2 in separators_double:
                            self.__list.append(aux + aux2)
                        else:
                            self.__list.append(aux)
                            self.back()
                elif aux in separators:
                    if temporary_string != '':
                        self.__list.append(temporary_string)
                    temporary_string = ""
                    aux2 = self.get()
                    if aux + aux2 in separators_double:
                        self.__list.append(aux + aux2)
                    else:
                        self.__list.append(aux)
                        self.back()
                elif aux in ['&', '|']:
                    if temporary_string != '':
                        self.__list.append(temporary_string)
                    temporary_string = ""
                    aux2 = self.get()
                    if aux + aux2 in separators_double:
                        self.__list.append(aux + aux2)
                    else:
                        raise Exception("Syntax wrong bitch")
                elif aux in string.whitespace:
                    if temporary_string != '':
                        self.__list.append(temporary_string)
                    temporary_string = ""
                else:
                    temporary_string += aux
            except IndexError:
                self.back()
                aux = self.get()
                if aux in separators:
                    self.__list.append(aux)
                return '\0'

    """
    Afiseaza lista dupa ce apeleaza celelalte functii
    """

    def run(self):
        self.read()
        self.parser()
        self.make_fip()
        output_file = "out.txt"
        with open(output_file, "w") as file:
            # file.write("-" * 25 + "\n")
            # file.write(f'{"ATOM":7} {"COD_ATOM":10} {"COD_TS":6}' + "\n")
            # file.write("-" * 25 + "\n")
            x = 0
            for i in self.__list:
                # file.write(f'{i:7} '
                #            f'{str(self.__cod_atom[x]):10} '
                #            f'{str(self.__cod_ts[x]) if self.__cod_ts[x] != -1 else "-":6}' + "\n")
                file.write(f'{i} {self.__cod_atom[x]}\n')
                x += 1
            x = 0
Exemplo n.º 30
0
def GetSprite(sprite):
    return HashTable.HTlookUp(FTSMain.SPRITETABLE, SPRITEHASHFUNCTION, sprite)
Exemplo n.º 31
0
def SpritesInit():
    FTSMain.SPRITETABLE = HashTable.CreateHashTable(FTSMain.TABLESIZE)
Exemplo n.º 32
0
 def create_new_hash_table(self):
     self.hash_table = HashTable()