Example #1
0
def main():
    print("What kind of tree do you want?")
    print("Type the number.")
    kind_of_tree = input("1. Red Black Tree\n2. AVL Tree\n3. BTree\n")
    if kind_of_tree == '1':
        rb_tree = set_rb("words.txt")
        print("Red Black Tree:")
        print_tree(rb_tree.root)
        print()
        print("Anagrams in the word file for spot:")
        rb_tree.print_anagrams("spot")
        print()
        print("Number of anagrams for spot: " + str(count_anagrams("spot", rb_tree)))
        print(greatest_number_of_anagrams("words2.txt", rb_tree))
    elif kind_of_tree == '2':
        AVL_Tree = set_avl("words3.txt")
        print()
        print("AVL Tree:")
        print_tree(AVL_Tree.root)
        print()
        print("Anagrams in the word file for abort:")
        AVL_Tree.print_anagrams("abort")
        print()
        print("Number of anagrams for team: " + str(count_anagrams("team", AVL_Tree)))
    elif kind_of_tree == '3':
        BTree = create_btree("words.txt")
        print("BTree: ")
        BTree.print()
        print()
        BTree.print_anagrams("spot")
        print()
        print("Number of anagrams for spot: " + str(count_anagrams("spot", BTree)))
        print(greatest_number_of_anagrams("words2.txt", BTree))
Example #2
0
 def __init__(self):
     self._members = BTree()
     # Create the default properties.
     self._setProperty('email', '', 'string')
     self._setProperty('portal_skin', '', 'string')
     self._setProperty('listed', '', 'boolean')
     self._setProperty('login_time', '2000/01/01', 'date')
     self._setProperty('last_login_time', '2000/01/01', 'date')
Example #3
0
def insert(x, B):
    if B == None:
        B = BTree([x])
    else:
        if (2 * BTree.degree - 1 == B.nbKeys):
            R = BTree([], [B])
            split(R, 0)
            B = R
        __insert(x, B)
    return B
Example #4
0
 def _comp_turn(self):
     """
     Provides realization of computer turn in a game.
     """
     board_copy = self.data.copy_board()
     root = BNode(board_copy)
     new_tree = BTree()
     new_tree.root = root
     new_tree.expand()
     i, j = (int(k) for k in new_tree.get_best_index())
     self.data.set_value([i, j], -1)
     print("Ей-айовий turn:")
     print(self)
Example #5
0
def create_btree(words):
    # create an btree
    btree = BTree(max_num_keys=6)
    # read the file
    file2 = open(words, "r")
    line = file2.readline()
    # while loop to read all lines in file
    while line:
        # each word is added to the btree
        new_word = line.rstrip().lower()
        btree.insert(new_word)
        line = file2.readline()
    # return the tree
    return btree
    def __init__(self, input_file, output_file, MMB, index_type):

        self.input_file = input_file
        self.output_file = output_file
        self.MMB = MMB

        if index_type == "btree":
            self.index = BTree()
        elif index_type == "hash":
            self.index = MyHash()
        else:
            print("Invalid index type")
            exit(-1)

        self.dup_open()

        while True:
            rec = self.get_next()

            # input file finished
            if rec == None:
                self.flush_output()
                break

            # append the record to output buffer if unique
            if not self.index.search(rec):
                self.out_buff.append(rec)
                self.index.insert(rec)

            # if output buffer is full then flush the output
            if len(self.out_buff) >= self.NTB:
                self.flush_output()

        self.dup_close()
Example #7
0
def file_to_b_tree(filename):
    b_tree = BTree(3)  # creates an empty binary search tree
    file = open(filename, "r",
                encoding="utf-8")  # opens file and stores it as an object

    with file as f:  # enables better syntax and exception handling
        line = f.readline().split(None, 1)  # splits after the first word
        while line:  # checks if file is empty
            if re.compile('[a-zA-Z]').search(
                    line[0]
                [0]) is not None:  # checks if first char is a letter
                b_tree.insert(line)  # adds it to bst if so

            line = f.readline().split(None, 1)

    return b_tree
Example #8
0
class Run:

    print("##################################################################")
    print("------ Binary Tree ------")
    nodes = [4, 5, 7, 8, 11, 23, None, 22, None, 45, 100, 200, 500]
    bTree = BTree(nodes)
    bTree.process()
Example #9
0
 def insertB(self, elementMatriz, elementB):
     if (elementMatriz != None):
         if (elementMatriz.accesoB == None):
             bbtre = BTree(5)
             elementMatriz.accesoB = bbtre
             bbtre.add(elementB)
             # metodo opcional
             tempT = tBTree()
             elementMatriz.accesB = tempT
             nodeBT = NodeTree(elementB)
             tempT.insert(nodeBT)
         else:
             elementMatriz.accesoB.add(elementB)
             # metodo opcional
             nodeBT = NodeTree(elementB)
             elementMatriz.accesB.insert(nodeBT)
Example #10
0
def test_underflow_second_child_reverse_order():
    tree = BTree()
    for x in range(1, 6):
        tree.insert(x)
    tree.delete(5)
    tree.delete(4)
    assert tree.json() == '[2, [1], [3]]'
Example #11
0
def test_underflow_first_child_reverse_order():
    tree = BTree()
    for x in range(1, 6):
        tree.insert(x)
    tree.delete(2)
    tree.delete(1)
    assert tree.json() == '[4, [3], [5]]'
Example #12
0
    def hybrid_training(self, threshold=100):
        for i in range(self.stage_num):
            for j in range(self.cfg.stages[i]):
                # Build model according to different stages
                model, criterion, optimizer = self.build_model(level=i)

                # In case of empty tmp_x train data
                if self.tmp_x[i][j]:
                    self.index[i][j] = self.train(self.tmp_x[i][j],
                                                  self.tmp_y[i][j],
                                                  model,
                                                  criterion,
                                                  optimizer,
                                                  val_ratio=0.1)

                # Update training example for next level model
                if i < self.stage_num - 1:
                    for r in range(len(self.tmp_x[i][j])):
                        p = self.index[i][j](torch.FloatTensor(
                            [self.tmp_x[i][j][r]]))
                        if self.cfg.feature_scale == True:
                            p = int(p * self.cfg.stages[i + 1])
                        else:
                            p = int(p)
                        if p > self.cfg.stages[i + 1] - 1:
                            p = self.cfg.stages[i + 1] - 1

                        self.tmp_x[i + 1][p].append(self.tmp_x[i][j][r])
                        self.tmp_y[i + 1][p].append(self.tmp_y[i][j][r])

        # If MAE(Maximum Absolute Error) of a ML model is greater than threshold, then we replace it with a BTree structure
        last = self.stage_num - 1
        for j in range(len(self.index[last])):
            if self.index[last][j]:
                input_x = torch.FloatTensor([self.tmp_x[last][j]]).view(-1, 1)
                true_y = torch.FloatTensor(self.tmp_y[last][j]).view(-1, 1)
                pred_y = self.index[last][j](input_x)
                mae = self.max_abs_err(pred_y, true_y).item()
                if mae > threshold:
                    btree = BTree(32)
                    for key, pos in zip(self.tmp_x[last][j],
                                        self.tmp_y[last][j]):
                        btree.insert(Item(key, pos))
                    self.index[last][j] = btree
        self.save_index()
Example #13
0
def main():
    BT = BTree(BTNode(125))
    for i in range(0, 100):
        BT.insert(random.randint(0, 500))

    BT.inorder()
    while True:
        print(BT.contains(int(input('Whats your Query? '))))
Example #14
0
 def add_genere(self,year, data):
     genere_to_add = Genere()
     genere_to_add.arbol = BTree(3)
     genere_to_add.genere = data
     col_genere = year.generes.search_genere(genere_to_add.genere)
     if col_genere is None:
         genere = year.generes.add(genere_to_add)
         return genere
     else:
         return col_genere
Example #15
0
def __fromList(s, i=0):
    if i < len(s) and s[i] == '(':
        i += 2
        B = BTree()
        while s[i] != '>':
            key = ""
            while not (s[i] in ',>'):  # s[i] != ',' and s[i] != '>'
                key += s[i]
                i += 1
            B.keys.append(int(key))
            if s[i] == ',':
                i += 1
        i += 1  # to pass the '>'
        B.children = []
        while s[i] != ')':
            (C, i) = __fromList(s, i)
            B.children.append(C)
        i += 1
        return (B, i)
Example #16
0
    def __init__(self):
        super(MainWindow, self).__init__()

        loadUi("graphic.ui", self)
        self.btree = BTree(self.grade_sb.value())

        self.le_data.returnPressed.connect(self.insert)
        self.btn_clear.clicked.connect(self.clear)
        self.bt_add.clicked.connect(self.insert)
        self.btn_remove.clicked.connect(self.remove)
        self.grade_sb.valueChanged.connect(self.grade_changed)

        img_add = QIcon('img/add')
        img_del = QIcon('img/del')
        img_clean = QIcon('img/clean') #TODO add img clear

        self.bt_add.setIcon(img_add)
        self.btn_remove.setIcon(img_del)
        self.btn_clear.setIcon(img_clean)
Example #17
0
def split(B, i):
    mid = BTree.degree - 1
    L = B.children[i]
    R = BTree()
    # Keys
    (L.keys, x, R.keys) = (L.keys[:mid], L.keys[mid], L.keys[mid + 1:])
    # Children
    if L.children != []:
        (L.children, R.children) = (L.children[:mid + 1], L.children[mid + 1:])
    # Root
    B.keys.insert(i, x)
    B.children.insert(i + 1, R)
def constructInvertedIndex():
    global dictionary
    dictionary = BTree(Node("سسسسسس", 1, []))
    nodesList = []
    docCounter = 0
    for news in getNewsList():
        nodes = {}
        position = 0
        for term in tokenize(normalize(news.content), check_finglish):
            if term != invalidToken:
                nodes[dictionary.addOccurrence(term, news.id, position)] = True
            position += 1
        nodesList.append(nodes)
        for node in nodes:
            node.cal_tf(news.id)
        docCounter += 1
        if docCounter % 20 == 0:
            Laws.heap(getDictionary())
    calAllIdf(dictionary.root)

    i = 0
    for news in getNewsList():  # calculate the documents' normalize factors for 3 scoring schemes
        nodes = nodesList[i]
        sum_of_squares_1 = 0
        sum_of_squares_2 = 0
        sum_of_squares_3 = 0
        for node in nodes.keys():
            sum_of_squares_1 += math.pow((getTf(news.id, node.postingsList) - 1) * node.idf, 2)
            sum_of_squares_2 += math.pow(getTf(news.id, node.postingsList), 2)
            sum_of_squares_3 += math.pow(getTf(news.id, node.postingsList) * node.idf, 2)
        normalizationFactorsScheme1.append(math.sqrt(sum_of_squares_1))
        normalizationFactorsScheme2.append(math.sqrt(sum_of_squares_2))
        normalizationFactorsScheme3.append(math.sqrt(sum_of_squares_3))
        i += 1

    Laws.storeHeapDataSet()
    storeDictionary(dictionary)
    storeNormFactors()
Example #19
0
 def __init__(self,
              entries,
              order=100,
              shared=None):  # entries must be a  dicionary
     self.merge_lock = Semaphore(value=1)
     self.time_lock = Semaphore(value=1)
     self._psbt = BTree.bulkload(entries, order)
     self.shared = shared
     self.started = False
     self.threads = []
     self.leaves = []
     self.folded = Queue(maxsize=1)
     self.final = Queue(maxsize=1)
     self.merge_lock = Lock()
Example #20
0
def create_btree(file_name):
    try:
        english_words = BTree(max_num_keys=3)

        # Open file and read first line
        file = open(file_name, "r")
        line = file.readline()

        if line == "":
            print("Selected file is empty")
            main()

        # Loop to read all lines in the file
        while line:
            # Add each word from the list
            new_word = line.rstrip().lower()
            english_words.insert(new_word)
            line = file.readline()

        return english_words
    except FileNotFoundError:
        print("File not found. Please try again.")
        main()
Example #21
0
    def test_insertion( self ):
        data = [ ( 2, 5 ), ( 4, 3 ), ( 1, 10 ), ( 3, 7 ), ( 8, 10 ), ( 7, 5 ), ( 9, 3 ), ( 6, 11 ), ( 5, 14 ) ]
        
        B = BTree( 2 )
        for key, value in data:
            B.insert( key, value )

        print ""
        print B.dump()
        
        res1 = B.query( 2, 5 )
        self.assertEqual( res1, [ ( 2, 5 ), ( 3, 7 ), ( 4, 3 ), ( 5, 14 ) ] )
        res2 = B.query( 3, 9 )
        self.assertEqual( res2, [ ( 3, 7 ), ( 4, 3 ), ( 5, 14 ), ( 6, 11 ), ( 7, 5 ), ( 8, 10 ), ( 9, 3 ) ] )
Example #22
0
def main():
    parser = argparse.ArgumentParser(description='Get stats of btree')
    parser.add_argument('--data', type=str, help='data file')
    parser.add_argument('--order',
                        type=int,
                        default='3',
                        help='order of the btree')
    args = parser.parse_args()

    tree = BTree(args.order)

    loadTree(tree, args.data)
    with open('data', 'r') as file:
        data = file.readlines()

    collectData(tree.insert, 'insert', data, tree)
    collectData(tree.find, 'find', data, tree)
    collectData(tree.delete, 'delete', data, tree)
Example #23
0
class Search():
    def __init__(self):
        self.arbolB = BTree(3)
        self.crawler = Crawler(self.arbolB)
        self.iniciar_crawler()

    def pedir_ingreso(self):
        return input(
            "Ingrese las palabras que desea buscar: (Ingrese 'F' para terminar la búsqueda o 'R' para reiniciar el crawler.)\n"
        )

    def buscar(self):
        ingreso = self.pedir_ingreso()
        # ps = PorterStemmer()
        while not ingreso.lower() == 'f':
            if ingreso.lower() == 'r':
                break

            palabras = ingreso.split()
            for palabra in palabras:
                self.mostrar_paginas(palabra, self.buscar_palabra(palabra))
                # self.mostrar_paginas(palabra, self.buscar_palabra(ps.stem(palabra)))
            ingreso = self.pedir_ingreso()
        if ingreso.lower() == 'r':
            self.iniciar_crawler()

    '''
        Recibe una cadena a buscar en las palabras
        devueltas por el Crawler y devuelve las palabras
        encontradas con su pagina correspondiente
    '''

    def buscar_palabra(self, palabra):
        palabraDocumentos = self.arbolB.obtener_documentos(palabra)
        return palabraDocumentos

    def mostrar_paginas(self, palabra, pagina):
        print((palabra, pagina))

    def iniciar_crawler(self):
        print("Crawler iniciado, para interrumpirlo presione Ctrl + C \n")
        self.crawler.iniciar()
        self.buscar()
Example #24
0
from Functions import Functions
from ManipulateData import ManipulateData
from BTree import BTree
from Hash import HashMap

mostrar = Functions()
data_functions = ManipulateData()
B = BTree()
B.populate_tree()

H = HashMap()
H.populate_hash()


def show_admin_menu():
    print()
    print('-------------------------------------------------------------')
    print('-----------------Menu de Admin-------------------------------')
    print('-------------------------------------------------------------')
    print('1 - Ordenar arquivo de dados')
    print('2 - Mostrar todos os dados')
    print('3 - Busca binária por ID')
    print('4 - Criar arquivo de índices por ID')
    print('5 - Criar arquivo de índices por Nome')
    print('6 - Ordenar índices por Nome')
    print('7 - Criar indices por id com salto')

    option1 = int(input('Informe a opção: '))

    if option1 is 1:
        data_functions.ordenar()
Example #25
0
class MainWindow(QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()

        loadUi("graphic.ui", self)
        self.btree = BTree(self.grade_sb.value())

        self.le_data.returnPressed.connect(self.insert)
        self.btn_clear.clicked.connect(self.clear)
        self.bt_add.clicked.connect(self.insert)
        self.btn_remove.clicked.connect(self.remove)
        self.grade_sb.valueChanged.connect(self.grade_changed)

        img_add = QIcon('img/add')
        img_del = QIcon('img/del')
        img_clean = QIcon('img/clean') #TODO add img clear

        self.bt_add.setIcon(img_add)
        self.btn_remove.setIcon(img_del)
        self.btn_clear.setIcon(img_clean)

    def clear(self):
        self.tree_lb.clear()
        self.btree = BTree(self.grade_sb.value())
        self.lw_operations.clear()

    def grade_changed(self, grade):
        self.btree = BTree(grade)
        self.tree_modified()

    def insert(self):
        value = self.le_data.text()

        try:
            self.btree.insert(float(value))
            self.tree_modified()
            self.lw_operations.addItem('Insertado: %s' %value)
        except ValueError:
            QMessageBox.information(self, "Información", "El valor entrado no es correcto.")
        finally:
            self.le_data.clear()

    def remove(self):
        value = self.le_data.text()

        try:
            self.btree.delete(float(value))
            self.tree_modified()
            self.lw_operations.addItem('Eliminado: %s' % value)
        except ValueError:
            QMessageBox.information(self, "Información", "El valor entrado no es correcto.")
        finally:
            self.le_data.clear()
            self.le_data.setFocus()

    def tree_modified(self):
        graph = pydot.Dot(graph_type='digraph', ratio='fill')

        is_empty = self.btree.root is None or not self.btree.root.keys
        idd = 1
        nodes = [] if is_empty else [(self.btree.root, idd)]

        while nodes:
            parent, iid = nodes.pop(0)
            value = '|'.join(map(self.to_str, parent.keys))

            dot_parent = pydot.Node(iid, shape='square', label = value)

            graph.add_node(dot_parent)

            for child in [ch for ch in parent.sons if ch is not None]:
                idd+= 1
                nodes.append((child, idd))
                value = '|'.join(map(self.to_str, child.keys))
                
                dot_node = pydot.Node(idd, shape='square', label = value)
                graph.add_node(dot_node)

                graph.add_edge(pydot.Edge(dot_parent, dot_node))

        if is_empty:
            image = QPixmap()
        else:
            _bytes = graph.create(format='png')
            image = QPixmap()
            image.loadFromData(_bytes)

        self.tree_lb.setPixmap(image)

    @staticmethod
    def to_str(number):
        if number.is_integer():
            return str(int(number))
        return str(number)
Example #26
0
# Set up a BTree to allow testing of delete functionality in REPL.
from BTree import BTree
import random

if __name__ == '__main__':
    tree = BTree()
    [tree.insert(i) for i in random.sample(range(0, 10), 10)]
    tree.display()
Example #27
0
 def test_left_of_root_not_is_none(self):
     b = BTree()
     b.insert(2)
     b.insert(1)
     self.assertNotEqual(b.root.left, None)
Example #28
0
 def test_right_of_left_root_not_is_none(self):
     b = BTree()
     b.insert(4)
     b.insert(2)
     b.insert(3)
     self.assertNotEqual(b.root.left.right, None)
Example #29
0
 def test_right_of_right_root_not_is_none(self):
     b = BTree()
     b.insert(4)
     b.insert(5)
     b.insert(6)
     self.assertNotEqual(b.root.right.right, None)
Example #30
0
 def test_insert_root_with_left_none(self):
     b = BTree()
     b.insert(2)
     self.assertIsNone(b.root.left)
Example #31
0
from BTree import BTree
from PalabraDocumentos import PalabraDocumentos

arbol = BTree(3)
# arbol.insertar('untref')
# arbol.insertar('computacion')
# arbol.insertar('ingenieria')
# for i in range(20)
arbol.insertar(PalabraDocumentos('untref', ['link']))
arbol.insertar(PalabraDocumentos('computacion', ['link 2']))
arbol.insertar(PalabraDocumentos('ingenieria', ['link 3']))
arbol.insertar(PalabraDocumentos('gato', ['link 4']))
arbol.insertar(PalabraDocumentos('perro', ['link 5']))
arbol.insertar(PalabraDocumentos('muntref', ['link']))
arbol.insertar(PalabraDocumentos('computadora', ['link 2']))
arbol.insertar(PalabraDocumentos('ingeniero', ['link 3']))
arbol.insertar(PalabraDocumentos('gata', ['link 4']))
arbol.insertar(PalabraDocumentos('perra', ['link 5']))
arbol.insertar(PalabraDocumentos('xuntref', ['link']))
arbol.insertar(PalabraDocumentos('computo', ['link 2']))
arbol.insertar(PalabraDocumentos('ingeniera', ['link 3']))
arbol.insertar(PalabraDocumentos('garra', ['link 4']))
arbol.insertar(PalabraDocumentos('perrera', ['link 5']))
# arbol.insertar(3)
# arbol.insertar(4)
# arbol.insertar(2)
# arbol.insertar(1)
# arbol.insertar(15)
# arbol.insertar(57)
# arbol.insertar(52)
# arbol.insertar(24)
Example #32
0
def ReSplit(data, merge_cutoff=0.1, weight=1, max_k=10, max_ndim=2, bic='bic'):

    root = BTree(('leaf', ))
    root.indices = data.index.values.tolist()
    root.weight = weight
    #if len(root.indices) < 500:
    #    print(root.indices)

    if data.shape[0] < 2:
        root.all_clustering_dic = _set_small_leaf(data)
        root.stop = 'small size'
        return root

    unimodal = GaussianMixture(1, covariance_type='full').fit(data)
    root.ll = root.weight * unimodal.lower_bound_
    root.bic = unimodal.bic(data)

    separable_features, bipartitions, scores_ll, bic_list, all_clustering_dic = HiScanFeatures(
        data, root, merge_cutoff, max_k, max_ndim, bic)

    if len(separable_features) == 0:
        root.all_clustering_dic = all_clustering_dic
        root.stop = 'no separable features'
        return root
    '''
    scores_ll = np.zeros(len(separable_features))
    bic_list = np.zeros(len(separable_features))
    for fidx in range(len(separable_features)):
        f = separable_features[fidx]
        if np.sum(bipartitions[f]) < 2 or np.sum(~bipartitions[f]) < 2:
            continue
        gmm1 = GaussianMixture(1,covariance_type='full').fit(data.loc[bipartitions[f],:])
        ll1 = gmm1.lower_bound_ * sum(bipartitions[f])/len(bipartitions[f])
        bic1 = gmm1.bic(data.loc[bipartitions[f],:]) 
        
        gmm0 = GaussianMixture(1,covariance_type='full').fit(data.loc[~bipartitions[f],:])
        ll0 = gmm0.lower_bound_ * sum(~bipartitions[f])/len(bipartitions[f])
        bic0 = gmm0.bic(data.loc[~bipartitions[f],:]) 
        
        scores_ll[fidx] = (ll1 + ll0) * root.weight - root.ll
        bic_list[fidx] = bic1 + bic0
    '''
    #print(separable_features)
    #print(scores_ll)
    #print(bic_list)
    idx_best = np.argmax(scores_ll)
    if np.max(scores_ll) < 0.001:
        #if root.bic < bic_list[idx_best]:
        root.stop = 'spliting increases bic'
        return root

    #idx_best = np.argmax(scores_ent)
    best_feature = separable_features[idx_best]
    best_partition = bipartitions[best_feature]
    #best_weights = all_clustering_dic[len(best_feature)][best_feature]['weight']

    ## construct current node
    root.key = best_feature
    root.all_clustering_dic = all_clustering_dic
    #root.marker_summary = marker_summary
    #root.para = para

    ## branch cells, component with higher mean goes right.
    p1_mean = data.loc[best_partition, best_feature].mean(0)
    p2_mean = data.loc[~best_partition, best_feature].mean(0)

    flag = True
    if len(p1_mean) == 1:
        flag = p1_mean.values > p2_mean.values
    else:
        p1_cosine = sum(p1_mean) / np.sqrt(sum(p1_mean**2))
        p2_cosine = sum(p2_mean) / np.sqrt(sum(p2_mean**2))
        flag = p1_cosine > p2_cosine

    if flag:
        child_right = data.iloc[best_partition, :]
        w_r = sum(best_partition) / len(best_partition)
        child_left = data.iloc[~best_partition, :]
        w_l = sum(~best_partition) / len(best_partition)
        root.where_dominant = 'right'
    else:
        child_right = data.iloc[~best_partition, :]
        w_r = sum(~best_partition) / len(best_partition)
        child_left = data.iloc[best_partition, :]
        w_l = sum(best_partition) / len(best_partition)
        root.where_dominant = 'left'

    ## recursion
    root.left = ReSplit(child_left, merge_cutoff, weight * w_l, max_k,
                        max_ndim, bic)
    root.right = ReSplit(child_right, merge_cutoff, weight * w_r, max_k,
                         max_ndim, bic)

    return root
Example #33
0
 def clear(self):
     self.tree_lb.clear()
     self.btree = BTree(self.grade_sb.value())
     self.lw_operations.clear()
Example #34
0
 def __init__(self, element, color=BLACK):
     BTree.__init__(self, element)
     self.color = color
Example #35
0
 def grade_changed(self, grade):
     self.btree = BTree(grade)
     self.tree_modified()
Example #36
0
class MemberDataTool (UniqueObject, SimpleItem, PropertyManager):
    '''This tool wraps user objects, making them act as Member objects.
    '''
    id = 'portal_memberdata'
    meta_type = 'CMF Member Data Tool'
    _v_temps = None
    _properties = ()

    security = ClassSecurityInfo()

    manage_options=( ( { 'label' : 'Overview'
                       , 'action' : 'manage_overview'
                       }
                     , { 'label' : 'Contents'
                       , 'action' : 'manage_showContents'
                       }
                     )
                   + PropertyManager.manage_options
                   + SimpleItem.manage_options
                   )

    #
    #   ZMI methods
    #
    security.declareProtected( CMFCorePermissions.ManagePortal
                             , 'manage_overview' )
    manage_overview = DTMLFile( 'explainMemberDataTool', _dtmldir )

    security.declareProtected( CMFCorePermissions.ViewManagementScreens
                             , 'manage_showContents')
    manage_showContents = DTMLFile('memberdataContents', _dtmldir )

    security.declareProtected( CMFCorePermissions.ViewManagementScreens
                             , 'getContentsInformation',)


    def __init__(self):
        self._members = BTree()
        # Create the default properties.
        self._setProperty('email', '', 'string')
        self._setProperty('portal_skin', '', 'string')
        self._setProperty('listed', '', 'boolean')
        self._setProperty('login_time', '2000/01/01', 'date')
        self._setProperty('last_login_time', '2000/01/01', 'date')

    #
    #   'portal_memberdata' interface methods
    #
    security.declarePrivate('getMemberDataContents')
    def getMemberDataContents(self):
        '''
        Return the number of members stored in the _members
        BTree and some other useful info
        '''
        membertool   = getToolByName(self, 'portal_membership')
        members      = self._members
        user_list    = membertool.listMemberIds()
        member_list  = members.keys()
        member_count = len(members)
        orphan_count = 0

        for member in member_list:
            if member not in user_list:
                orphan_count = orphan_count + 1

        return [{ 'member_count' : member_count,
                  'orphan_count' : orphan_count }]

    security.declarePrivate( 'searchMemberDataContents' )
    def searchMemberDataContents( self, search_param, search_term ):
        """ Search members """
        res = []

        if search_param == 'username':
            search_param = 'id'

        for user_wrapper in self._members.values():
            searched = getattr( user_wrapper, search_param, None )
            if searched is not None and string.find( searched, search_term ) != -1:
                res.append( { 'username' : getattr( user_wrapper, 'id' )
                            , 'email' : getattr( user_wrapper, 'email', '' )
                            }
                          )

        return res

    security.declarePrivate('pruneMemberDataContents')
    def pruneMemberDataContents(self):
        '''
        Compare the user IDs stored in the member data
        tool with the list in the actual underlying acl_users
        and delete anything not in acl_users
        '''
        membertool= getToolByName(self, 'portal_membership')
        members   = self._members
        user_list = membertool.listMemberIds()

        for tuple in members.items():
            member_name = tuple[0]
            member_obj  = tuple[1]
            if member_name not in user_list:
                del members[member_name]

    security.declarePrivate('wrapUser')
    def wrapUser(self, u):
        '''
        If possible, returns the Member object that corresponds
        to the given User object.
        '''
        id = u.getUserName()
        members = self._members
        if not members.has_key(id):
            # Get a temporary member that might be
            # registered later via registerMemberData().
            temps = self._v_temps
            if temps is not None and temps.has_key(id):
                m = temps[id]
            else:
                base = aq_base(self)
                m = MemberData(base, id)
                if temps is None:
                    self._v_temps = {id:m}
                else:
                    temps[id] = m
        else:
            m = members[id]
        # Return a wrapper with self as containment and
        # the user as context.
        return m.__of__(self).__of__(u)

    security.declarePrivate('registerMemberData')
    def registerMemberData(self, m, id):
        '''
        Adds the given member data to the _members dict.
        This is done as late as possible to avoid side effect
        transactions and to reduce the necessary number of
        entries.
        '''
        self._members[id] = m
Example #37
0
from BTree import BTree


btree = BTree()
btree.insert(3)
btree.insert(2)
btree.insert(1)
btree.insert(4)
btree.print(None)

# import math

# class Circle:

#     def __init__(self, radius):
#         self.__radius = radius

#     def setRadius(self, radius):
#         self.__radius = radius

#     def getRadius(self):
#         return self.__radius

#     def area(self):
#         return math.pi * self.__radius ** 2

#     def __add__(self, another_circle):
#         return Circle( self.__radius + another_circle.__radius )

# c1 = Circle(4)
# print(c1.getRadius())
Example #38
0
# Simple test program
from BTree import BTree

if __name__ == "__main__":
    tree = BTree()
    for i in range(0, 7):
        tree.insert(i)
    tree.display()