Пример #1
0
 def __init__(self, name, user_id):
     # constructor
     self.name = name
     self.user_id = user_id
     self.accrued_fine = 0
     self.max_borrow = 5
     self.max_fine = 50
     self.my_item_list = ItemList()
Пример #2
0
class User:

    def __init__(self, name, user_id):
        # constructor
        self.name = name
        self.user_id = user_id
        self.accrued_fine = 0
        self.max_borrow = 5
        self.max_fine = 50
        self.my_item_list = ItemList()


    def __del__(self): # destructor
        pass


    def can_borrow(self):
        '''
        Check if user is allowed to borrow
        :return:
        '''
        len_items = self.my_item_list.len_items()# ask ItemList for length of list
        if ((len_items < self.max_borrow) and (self.accrued_fine < self.max_fine)): # check length of list against max_borrow
                                                                            # Check accrued fine less than max_fine
            is_any_overdue = self.my_item_list.is_any_overdue() # Ask ItemList if any items on ItemList are overdue
            can_borrow_ = not is_any_overdue # Flip False to True and True to False
        else:
            can_borrow_ = False
        return can_borrow_


    def checkout(self, item, date=None):
        '''
        Checkout book
        :param item:
        :return:
        '''

        self.my_item_list.check_out(item, date)# Ask ItemList to add item to list


    def ammend_fine(self, amount):
        '''
        add amount to self.accrued fine
        :param amount:
        :return:
        '''
        self.accrued_fine += amount


    def check_in(self, item):
        '''
        asks item list to check in item
        :param item:
        :return:
        '''
        fine = self.my_item_list.check_in(item)# ask itemlist to check in item
        self.accrued_fine += fine # add fine to accrued_fine
Пример #3
0
 def run_item_list(self):
     item_list = ItemList(self.user_id)
     while True:
         item_list.show_menu()
         key = input('Enter your command: ')
         if key == 'q':
             break
         elif key == '1':
             item_list.show_items()
         elif key == '2':
             item_list.add_to_cart()
    def __init__(self, figa, text, from_file=False, ffiltered=None, \
    flearned=None, tolerance=15, sf=False):
        '''
        Constructor. Creates Processor object.
        @param figa Path to file with figa outputs or memory reference
        @param text Path to file with text or memory reference
        @param from_file Reads data from files if True, otherwise reads
            data from memory
        @param ffiltered Path to file where filtered items will be written
        @param flearned Path to file where learned items will be written
        @param tolerance Number of chars between 2 words for method
            find_adjacent_names()
        @param sf Writes filtered names in file if True
        '''

        self.from_file = from_file

        if self.from_file:
            if figa and text:
                self.figa_doc = TextFile(figa, 'r')
                self.text_doc = TextFile(text, 'r')
            else:
                raise InputError('One or more paths are missing!')
        else:
            self.figa_doc = TextFile.from_text(figa)
            self.text_doc = TextFile.from_text(text)
            self.text_doc.content = self.text_doc.content.decode('utf-8')

        if flearned != None:
            self.llearned = TextFile(flearned, 'a')
        else:
            self.llearned = None

        # Load lists
        self.blacklist = ItemList.from_file(LIST_BLACKLIST)
        self.notfirst = ItemList.from_file(LIST_NOTFIRST)
        self.nationalities = ItemList.from_file(LIST_NATIONALITIES)
        self.replacements = ItemList.from_file(LIST_REPLACE)
        self.list_names = ItemList.from_file(LIST_NAMES)
        self.list_surrnames = ItemList.from_file(LIST_SURRNAMES)

        self.data_rows = DataRowList()
        self.name_list = DataRowList()
        self.initials = ItemList()

        self.tolerance = tolerance
        self.show_filtered = sf

        if sf and ffiltered != None:
            self.lfiltered = TextFile(ffiltered, 'w')
        else:
            self.lfiltered = None
Пример #5
0
def main():
    my_list = ItemList()
    print(ItemList) # TODO: Remove this print
    while True:
        # Display menu
        show_menu()
        
        # Get user input
        user_in = int(input())
        
        # Add item
        if user_in == 1:
            print("Add Item")
            my_item_title = input("Please enter To-Do item\n")
            my_item = Item(my_item_title)
            my_list.add_item(my_item)
            print("\n=> Added: " + my_item_title)
        
        # Remove item
        elif user_in == 2:
            print("  \nRemove Which Item?")
            show_list_items(my_list.userlist)
            item_to_remove = my_list.userlist[int(input()) - 1]
            my_list.remove_item(item_to_remove)
            print("\n=X= Removed: " + item_to_remove)

        # Show items in item_list
        elif user_in == 3:
            print("  \nYour List")
            show_list_items(my_list.userlist)

        # Mark item complete
        elif user_in == 4:
            print("  \nComplete?")
            show_list_items(my_list.userlist)
            my_list.userlist[int(input()) - 1].complete = True
            show_list_items(my_list.userlist)

        # Sort by date
        elif user_in == 5:
            print("  \nSort by Date added (Reverse Chron)")
            my_list.userlist.sort(key = lambda x: x.date, reverse = True)
            show_list_items(my_list.userlist)

        # Sort by complete
        elif user_in == 6:
            print("  \nSort by Complete")
            my_list.userlist.sort(key = lambda x: x.complete, reverse = True)
            show_list_items(my_list.userlist)

        # Exit program
        elif user_in == 0:
            exit(0)

        else:
            print("invalid menu option")
    def replace_parts(self):
        '''
        Checks if string or it's part is in replace list and replaces it with
        empty string accordingly.
        '''

        for i in range(self.name_list.size()):
            for rp in self.replacements:
                if rp in self.name_list[i].value:
                    p_rp = ItemList.get_parts(rp)
                    p_nli = self.name_list[i].parts

                    if len(p_rp) < len(p_nli):
                        is_whole = True
                        for r in p_rp:
                            for n in p_nli:
                                if r in n and not r == n:
                                    is_whole = False
                                    break

                        if is_whole:
                            self.name_list[i].set_value(\
                                self.name_list[i].value.replace(rp, '').strip())
Пример #7
0
    def _populate_task_list(self):
        """
        Build the main task list for selection of outputs, items, etc.
        """

        # clear existing widgets:
        task_scroll_widget = self._ui.task_scroll.widget()
        self._group_widget_info = {}
        #TODO

        if len(self._tasks) == 0:
            # no tasks so show no tasks text:
            self._ui.publishes_stacked_widget.setCurrentWidget(
                self._ui.no_publishes_page)
            return
        else:
            self._ui.publishes_stacked_widget.setCurrentWidget(
                self._ui.publishes_page)

        # group tasks by display group:
        group_order = []
        tasks_by_group = {}
        for task in self._tasks:
            group = tasks_by_group.setdefault(task.output.display_group,
                                              dict())

            # track unique outputs for this group maintaining order
            # respective to task
            group_outputs = group.setdefault("outputs", list())
            if task.output not in group_outputs:
                group_outputs.append(task.output)

            # track unique items for this group maintaining order
            # respective to task
            group_items = group.setdefault("items", list())
            if task.item not in group_items:
                group_items.append(task.item)

            # track tasks for this group:
            group.setdefault("tasks", list()).append(task)

            if not task.output.display_group in group_order:
                group_order.append(task.output.display_group)

        # add widgets to scroll area:
        layout = task_scroll_widget.layout()
        for group in group_order:

            widget_info = {}

            # add header:
            header = GroupHeader(group, task_scroll_widget)
            layout.addWidget(header)
            widget_info["header"] = header

            # add output items:
            output_widgets = []
            for output in tasks_by_group[group]["outputs"]:
                item = OutputItem(output, task_scroll_widget)
                layout.addWidget(item)
                output_widgets.append(item)
            widget_info["output_widgets"] = output_widgets

            # add item list if more than one item:
            if self.expand_single_items or len(
                    tasks_by_group[group]["items"]) > 1:
                item_list = ItemList(tasks_by_group[group]["items"],
                                     task_scroll_widget)
                layout.addWidget(item_list)
                widget_info["item_list"] = item_list

            # always add error list:
            error_list = ErrorList(tasks_by_group[group]["tasks"],
                                   task_scroll_widget)
            #error_list.setVisible(False)
            layout.addWidget(error_list)
            widget_info["error_list"] = error_list

            self._group_widget_info[group] = widget_info

        # add vertical stretch:
        layout.addStretch(1)
class Processor(object):

    def __init__(self, figa, text, from_file=False, ffiltered=None, \
    flearned=None, tolerance=15, sf=False):
        '''
        Constructor. Creates Processor object.
        @param figa Path to file with figa outputs or memory reference
        @param text Path to file with text or memory reference
        @param from_file Reads data from files if True, otherwise reads
            data from memory
        @param ffiltered Path to file where filtered items will be written
        @param flearned Path to file where learned items will be written
        @param tolerance Number of chars between 2 words for method
            find_adjacent_names()
        @param sf Writes filtered names in file if True
        '''

        self.from_file = from_file

        if self.from_file:
            if figa and text:
                self.figa_doc = TextFile(figa, 'r')
                self.text_doc = TextFile(text, 'r')
            else:
                raise InputError('One or more paths are missing!')
        else:
            self.figa_doc = TextFile.from_text(figa)
            self.text_doc = TextFile.from_text(text)
            self.text_doc.content = self.text_doc.content.decode('utf-8')

        if flearned != None:
            self.llearned = TextFile(flearned, 'a')
        else:
            self.llearned = None

        # Load lists
        self.blacklist = ItemList.from_file(LIST_BLACKLIST)
        self.notfirst = ItemList.from_file(LIST_NOTFIRST)
        self.nationalities = ItemList.from_file(LIST_NATIONALITIES)
        self.replacements = ItemList.from_file(LIST_REPLACE)
        self.list_names = ItemList.from_file(LIST_NAMES)
        self.list_surrnames = ItemList.from_file(LIST_SURRNAMES)

        self.data_rows = DataRowList()
        self.name_list = DataRowList()
        self.initials = ItemList()

        self.tolerance = tolerance
        self.show_filtered = sf

        if sf and ffiltered != None:
            self.lfiltered = TextFile(ffiltered, 'w')
        else:
            self.lfiltered = None

    def read_data(self):
        '''
        Reads file contents and strore them as list data_rows.
        '''

        if self.figa_doc.invalid():
            raise InputError('Figa output is either empty or missing!')

        if self.text_doc.invalid() or self.text_doc.empty():
            raise InputError('Source text is either empty or missing!')

        lines = self.figa_doc.get_lines()
        if lines == [] or lines == None:
            return
        else:
            for line in lines:
                self.data_rows.add(DataRow(line))
            self.data_rows.sort()

    def write(self, path=None):
        '''
        Writes data_rows to file specified by path and closes files.
        @param path Path to file, if path is None then rows are written to STDOUT
        '''

        if not self.name_list.empty():
            self.name_list.sort()

            if path != None:
                f = open(path, 'w')
                for d in self.name_list.items:
                    f.write('{}\n'.format(d.__str__()))
                f.close()
            else:
                for d in self.name_list.items:
                    print('{}'.format(d.__str__()))
        else:
            print('No data to display!')

    def get_data(self):
        '''
        Get valid data rows.
        @return List of DataRows or empty list.
        '''

        dlist = []
        self.name_list.sort()

        if not self.name_list.empty():
            for d in self.name_list.items:
                if (len(d.value.strip().split(' ')) > 1):
                    dlist.append(d)
                else:
                    if self.lfiltered != None:
                        self.lfiltered.write('0\t{}\n'.format(d.value))
            return dlist
        else:
            return []

    def close_all(self):
        '''
        Closes all files used by Processor.
        '''

        self.text_doc.close()
        self.figa_doc.close()
        self.llearned.close()
        if self.lfiltered != None: self.lfiltered.close()

    def replace_parts(self):
        '''
        Checks if string or it's part is in replace list and replaces it with
        empty string accordingly.
        '''

        for i in range(self.name_list.size()):
            for rp in self.replacements:
                if rp in self.name_list[i].value:
                    p_rp = ItemList.get_parts(rp)
                    p_nli = self.name_list[i].parts

                    if len(p_rp) < len(p_nli):
                        is_whole = True
                        for r in p_rp:
                            for n in p_nli:
                                if r in n and not r == n:
                                    is_whole = False
                                    break

                        if is_whole:
                            self.name_list[i].set_value(\
                                self.name_list[i].value.replace(rp, '').strip())

    def mark_substrings(self):
        '''
        Removes all DataRows which values are substrings of other DataRows.
        '''

        for i in range(self.name_list.size()):
            for j in range(self.name_list.size()):
                if i != j and self.name_list[i] != None and \
                self.name_list[j] != None:
                    ilist = self.name_list[i].parts
                    jlist = self.name_list[j].parts

                    if len(ilist) > len(jlist):
                        all_in = True
                        for jp in jlist:
                            if not jp in ilist:
                                all_in = False

                        if all_in:
                            self.name_list[j].type = 8

        self.name_list.clean()

    def filter_names(self):
        '''
        Filters names from blacklist and invalid names (i.e. On June)
        '''

        names = self.name_list
        for i in range(self.name_list.size()):
            filtered = False
            name = names[i]

            if name.value == 'Test Testingson': continue

            if self.blacklist.contains(name.value) or \
            self.replacements.contains(name.value):
                names.filter(i, 1)
                continue

            for bl in self.blacklist:
                if bl in name.value:
                    names.filter(i, 1)
                    filtered = True
                    break
            if filtered: continue

            if self.notfirst.contains(name.first()):
                names.filter(i, 2)
                continue

            if  not self.list_names.contains(name.first()) and \
            name.first() not in self.initials:
                names.filter(i, 3)
                continue

            invalid = False
            for p in name.parts:
                if self.nationalities.contains(p):
                    invalid = True
                    break
            if invalid:
                names.filter(i, 5)
                continue

            # Filter names containing only initials
            all_initials = True
            for p in name.parts:
                if len(p) == 2 and p[1] == '.':
                    pass
                else:
                    all_initials = False

            if all_initials:
                names.filter(i, 6)
                continue

            # Do not remove (type 4), just mark
            if name.last() not in self.list_surrnames:
                name.type = 7
                continue

        if self.lfiltered != None and self.show_filtered == True:
            for x in names.filtered:
                self.lfiltered.write("{}\n".format(x.strip()))

        names.clean()

    def find_full_names(self):
        sentences = self.text_doc.content.split('.')
        names = []

        possible_name = []
        current_len = 0
        index = 0
        text = self.text_doc.content.replace('\n', ' ')
        for w in text.split(' '):
            if not w:
                current_len += len(w) + 1
                continue

            if w.endswith('.') or w.endswith(','):
                czech = False
                for letter in czech_letters:
                    if w.startswith(letter):
                        czech = True
                        break
                if (w[0].isupper() and len(w) > 1) or (czech and len(w) > 2):
                    possible_name.append(w[:-1])

                if possible_name and len(possible_name) > 1:
                    name = ' '.join(possible_name)
                    idr = DataRow.from_data(0, index + 1, index + len(name),
                                            name)
                    self.name_list.add(idr)
                possible_name = []
                index = 0

            else:
                czech = False

                for letter in czech_letters:
                    if w.startswith(letter):
                        czech = True
                        break

                if (w[0].isupper() and len(w) > 1) or (czech and len(w) > 2):
                    if not possible_name:
                        index = current_len

                    possible_name.append(w)

                else:
                    if len(possible_name) > 1:
                        name = ' '.join(possible_name)
                        idr = DataRow.from_data(0, index + 1,
                                                index + len(name), name)
                        self.name_list.add(idr)

                    possible_name = []
                    index = 0

            current_len += len(w) + 1

        if len(possible_name) > 1:
            name = ' '.join(possible_name)
            idr = DataRow.from_data(0, index + 1, index + len(name), name)
            self.name_list.add(idr)
        '''
        for s in sentences:
            words = s.split(' ')
            possible_name = []

            for w in words:
                if not w:
                    continue

                czech = False
                for letter in czech_letters:
                    if w.startswith(letter):
                        czech = True
                        break
                if w[0].isupper() and len(w) > 1:
                    possible_name.append(w)
                elif czech and len(w) > 2:
                    possible_name.append(w)
                else:
                    if len(possible_name) >= 2:
                        names.append(' '.join(possible_name))
                    possible_name = []


            if possible_name:
                names.append(' '.join(possible_name))

        print(names)
        for n in names:
            rgx = re.compile('({})'.format(n))
            matches = re.finditer(rgx, self.text_doc.content)
            for m in matches:
                idr = DataRow.from_data(0, m.start()+1, m.end(), n)
                self.data_rows.add(idr)
                self.name_list.add(idr)

        for p in self.get_data():
            print (p)

        self.data_rows.sort()
        '''

    def find_initials(self):
        '''
        Tries to find name initials in the text (J., A., etc.)
        '''

        text_parts = self.text_doc.content.split(' ')
        for p in text_parts:

            if len(p) == 2 and p[0].isupper() and p[1] == '.':
                self.initials.add(p)
            elif p.endswith('.'):
                for letter in czech_letters:
                    if p.startswith(letter):
                        self.initials.add(p)
                        break

        self.initials = set(self.initials)

        for i in self.initials:
            rgx = re.compile('({})'.format(i.replace('.', '\.')))
            matches = re.finditer(rgx, self.text_doc.content)
            for m in matches:
                idr = DataRow.from_data(10, m.start() + 1, m.end(), i)
                idr.initial = True
                self.data_rows.add(idr)

        self.data_rows.sort()

    def find_adjacent_names(self):
        '''
        Loops through data rows and attempts to find names.
        '''

        #if self.data_rows.empty():
        #    print('No data have beed read!')
        #    sys.exit(1)

        rows = self.data_rows
        for i in range(rows.size()):
            if len(rows[i].parts) != 1: continue
            if not rows[i].value[0].isupper():
                czech = False
                for letter in czech_letters:
                    if rows[i].value.startswith(letter):
                        czech = True
                        break
                if not czech:
                    continue

            parts = DataRowList.from_string(rows[i])
            if rows[i].processed:
                continue
            else:
                for j in range(i + 1, rows.size()):
                    if parts[-1].end_offset == rows[j].start_offset - 2 and \
                    (not parts.contains(rows[j].value) or rows[j].initial):
                        czech = False
                        for letter in czech_letters:
                            if rows[j].value.startswith(letter):
                                czech = True
                                break
                        if rows[j].value[0].isupper() or czech:
                            parts.add(rows[j])
                            rows[j].processed = True
                    else:
                        break

                rows[i].processed = True
                soff = parts[0].start_offset
                eoff = parts[-1].end_offset
                name = ''
                for p in parts:
                    name += p.value + ' '
                self.name_list.add(
                    DataRow.from_data(0, soff, eoff, name.strip()))

        for i in range(self.name_list.size()):
            if len(self.name_list[i].value.split(' ')) <= 1:
                self.name_list[i] = self.name_list[i].clear()

        self.name_list.clean()
        self.data_rows.clear_processed_flag()

    def find_incomplete_names(self):
        '''
        Search for unknown words after known words.
        '''

        chars = ['\'', '.']
        isep = ['.', ' ']  # separators of initals, e.g. "Aaaa A.A."
        rows = self.data_rows

        for i in range(rows.size()):
            if rows[i].processed:
                continue
            else:
                next_name = rows[i + 1] if i < rows.size() - 1 else None
                if not rows.has_follower(i):
                    start = rows[i].start_offset
                    word = rows[i].value + ' '
                    word_start = False
                    position = rows[i].end_offset + 1
                    if position >= self.text_doc.size():
                        break  # Nothing else to be found
                    if not self.text_doc.content[position].isupper():
                        continue
                    else:
                        tolerance = position + self.tolerance
                        char = self.text_doc.content[position]
                        while (char.isalpha() or char.isspace() or char in chars) and \
                        (position < tolerance or char != ' ') and (char != '\n'):
                            if word_start and not char.isupper():
                                break  # Not name, end loop
                            else:
                                word_start = False
                            if char == ' ':
                                word_start = True
                            if char == '.':
                                if not ((word[-2] == ' ' or word[-2] == '.') and \
                                word[-1].isupper()):
                                    break  # Not initial
                            word += char
                            position += 1
                            char = self.text_doc.content[position]
                        words = word.strip().split(' ')
                        words = [x for x in words if x]
                        name = []
                        for w in words:
                            if w not in name:
                                name.append(w)
                            else:
                                break
                        name = ' '.join(name)
                        end = start + len(name) - 1
                        self.name_list.add(DataRow.from_data(1, start, \
                            end, name))

        self.name_list.sort()
        self.solve_conflicts()

    def solve_conflicts(self):
        '''
        Finds conflicting names and concatenate them into one.
        '''

        names = self.name_list
        if names.size() < 2:
            return

        for i in range(names.size() - 1):
            if names[i].processed:
                continue

            if names[i].end_offset > names[i + 1].start_offset:
                firts, second = None, None
                if names[i].start_offset < names[i + 1].start_offset:
                    first = names[i]
                    second = names[i + 1]
                else:
                    first = names[i + 1]
                    second = names[i]

                fparts = first.parts
                sparts = second.parts
                for sp in sparts:
                    if sp not in fparts: fparts.append(sp)

                new_name = ' '.join(fparts)
                names[i].type = 4
                names[i].start_offset = first.start_offset
                names[i].end_offset = first.start_offset + len(new_name) - 1
                names[i].value = new_name
                names[i + 1].processed = True
                names[i + 1].clear()

        names.clear_processed_flag()
        names.clean()

    def separate_names_with_initials(self):
        '''
        Finds names containing initals and outputs them into file.
        '''

        fi = open(OUT_INITIALS, 'w')
        fn = open(OUT_NONINITIALS, 'w')
        for n in self.name_list.items:
            ok = False
            if '.' in n.value:
                pts = n.value.split(' ')
                for p in pts:
                    if '.' in p and len(p) == 2:
                        ok = True
                        break

            if ok:
                fi.write('{}\n'.format(n.value))
            else:
                fn.write('{}\n'.format(n.value))

        fi.close()
        fn.close()

    def remove_posessions(self):
        '''
        Removes "'s" from the end of names.
        '''

        names = self.name_list
        for i in range(names.size()):
            if names[i].length() > 2:
                if names[i].value[-2:] == "'s":
                    names[i].set_value(names[i].value[:-2])

    def remove_single_names(self):
        '''
        Removes names containing only 1 word.
        '''

        for i in range(self.name_list.size()):
            if len(self.name_list[i].get_parts()) <= 1:
                if self.lfiltered != None:
                    self.lfiltered.write('0\t{}\n'.format(
                        self.name_list[i].value))
                self.name_list.clear(i)
        self.name_list.clean()

    def try_to_learn(self):
        '''
        Learn new words.
        '''

        if self.data_rows == []:
            return

        for item in self.name_list.items:
            if item.type == 1:
                data = item.value.strip().split(' ')

                for i in range(len(data)):
                    in_names = self.list_names.contains(data[i])
                    in_snames = self.list_surrnames.contains(data[i])

                    if in_names == False and in_snames == False:
                        self.learn(data[i])

    def analyze(self):
        '''
        Preforms all Processor related actions.
        '''

        self.read_data()
        #if self.data_rows.empty():
        #    print('No data have beed read!')
        #    sys.exit(1)

        #self.find_initials()
        #self.find_adjacent_names()
        self.find_full_names()

        self.find_incomplete_names()
        self.replace_parts()

        #self.filter_names()

        # self.separate_names_with_initials()
        self.mark_substrings()
        self.remove_posessions()
        self.remove_single_names()
        self.try_to_learn()

    def learn(self, word):
        '''
        Writes newly learned word into learned.txt file.
        @param word String.
        '''

        if self.llearned != None:
            self.llearned.write('{}\n'.format(word))
Пример #9
0
 def python_create_item_list(items):
     py_rec = ItemList(CPyObject.toPy(ListStringHelper.c_data_set, items))
     return CPyRecord.fromPy(ItemList.c_data_set,
                             py_rec)  #to do: can be optional?
Пример #10
0
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent=parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.showMaximized()

        self.ui.txtFromDate.setDateTime(QtCore.QDateTime.currentDateTime())
        self.ui.txtFromDate.setCalendarPopup(True)
        self.ui.txtToDate.setDateTime(QtCore.QDateTime.currentDateTime())
        self.ui.txtToDate.setCalendarPopup(True)
        # init connection
        self.connection = create_open_database(host='localhost',port=3307,user='******',password='******',db_name='ksoft')
        # source_item_columns = []
        # target_item_columns = []
        # path = 'C:\\Users\\Kimsong\\Desktop\\Online Retail.xlsx'
        # result = import_from_excel(path,'Online Retail',source_item_columns,target_item_columns,connection)
        # print(result)
        header = self.ui.itemsetTableWidget.horizontalHeader()       
        header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
        header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
        header.setSectionResizeMode(2, QtWidgets.QHeaderView.Interactive)
        header.setSectionResizeMode(3, QtWidgets.QHeaderView.Stretch)

        header1 = self.ui.rulesTableWidget.horizontalHeader()       
        header1.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
        header1.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
        header1.setSectionResizeMode(2, QtWidgets.QHeaderView.Stretch)
        header1.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
        header1.setSectionResizeMode(4, QtWidgets.QHeaderView.Stretch)
        # end test connection
        # create event handler
        self.ui.actionImport_Items.triggered.connect(self.import_option_click)
        self.ui.actionItem_List.triggered.connect(self.item_list_click)
        self.ui.btnRunApriori.clicked.connect(self.run_apriori_click)
        self.ui.btnFilterItemset.clicked.connect(self.filter_itemset_click)
        # self.ui.chkShow.clicked.connect(self.show_checked)
        self.ui.btnFilterAnt.clicked.connect(self.filter_ant_click)
        self.ui.btnFilterConseq.clicked.connect(self.filter_conseq_click)
        # end create event handler
        self.getLastFilter()
        self.getItemsets()
        self.getRules() 
    def getLastFilter(self):
        record = get_last_apriori_filter(self.connection)
        if record == None:
            self.ui.lblFomDateFilter.setText("")
            self.ui.lblToDateFilter.setText("")
            self.ui.lblMinSupportFilter.setText("")
            self.ui.lblMinConfFilter.setText("")
        else:
            self.ui.lblFomDateFilter.setText((record[0]).strftime("%m/%d/%Y"))
            self.ui.lblToDateFilter.setText((record[1]).strftime("%m/%d/%Y"))
            self.ui.lblMinSupportFilter.setText(format(record[2],'0.4f'))
            self.ui.lblMinConfFilter.setText(format(record[3],'0.2f'))
    def getItemsets(self):
        chk = False
        contain = ''
        if(self.ui.chkShow.isChecked()):
            chk = True
        if len(self.ui.txtFilterContains.text()) > 0:
            contain = self.ui.txtFilterContains.text()
        
        pre_records = get_itemset_list(self.connection,chk,str(self.ui.lblMinSupportFilter.text()),contain)
        if not pre_records == None:
            self.ui.itemsetTableWidget.setRowCount(0)
            for row, record in enumerate(pre_records):
                self.ui.itemsetTableWidget.insertRow(row)
                self.ui.itemsetTableWidget.setItem(row,0,QtWidgets.QTableWidgetItem(str(record[0])))
                self.ui.itemsetTableWidget.setItem(row,1,QtWidgets.QTableWidgetItem(str(record[1])))
                self.ui.itemsetTableWidget.setItem(row,2,QtWidgets.QTableWidgetItem(str(record[2])))
                self.ui.itemsetTableWidget.setItem(row,3,QtWidgets.QTableWidgetItem(str(record[3])))
    def getRules(self):
        # select to list
        records = get_rules_list(self.connection,self.ui.txtFilterContainAnt.text(),self.ui.txtFilterContainConsq.text())
        self.ui.rulesTableWidget.setRowCount(0)
        for row, record in enumerate(records):
            self.ui.rulesTableWidget.insertRow(row)
            self.ui.rulesTableWidget.setItem(row,0,QtWidgets.QTableWidgetItem(str(record[0])))
            self.ui.rulesTableWidget.setItem(row,1,QtWidgets.QTableWidgetItem('->'))
            self.ui.rulesTableWidget.setItem(row,2,QtWidgets.QTableWidgetItem(str(record[1])))
            self.ui.rulesTableWidget.setItem(row,3,QtWidgets.QTableWidgetItem(format(record[2],'0.4f')))
            self.ui.rulesTableWidget.setItem(row,4,QtWidgets.QTableWidgetItem(format(record[3],'0.2f')))
    @pyqtSlot()
    def import_option_click(self):
        self.importForm = ImportData(self.connection)
        self.importForm.show()
    @pyqtSlot()
    def item_list_click(self):
        self.items = ItemList(self.connection)
        self.items.show()
    @pyqtSlot()
    def run_apriori_click(self):
        try:
            from_date = self.ui.txtFromDate.date()
            from_date = from_date.toPyDate()
            to_date = self.ui.txtToDate.date()
            to_date = to_date.toPyDate()
            min_support = self.ui.minSupportSpinBox.value()
            min_confidence = self.ui.minConfSpinBox.value()
            # preprocessing
            start_time = datetime.now()
            total_tran = generate_preprocessing(self.connection,from_date,to_date)
            # print("Trans : " + str(total_tran))
            filter_id = insert_apriori_filter(self.connection,from_date,to_date,min_support,min_confidence,total_tran)
            end_time = datetime.now()
            insert_activity_log(self.connection,filter_id,'matching',start_time,end_time)
            self.connection.commit()
            # start generate itemsets
            start_time = datetime.now()
            dataset = load_dataset(self.connection)
            # generating
            frequent_itemsets,support_data = apriori(dataset,min_support)
            end_time = datetime.now()
            insert_activity_log(self.connection,filter_id,'generate_itemset',start_time,end_time)
            insert_itemset(self.connection,support_data,total_tran)
            # self.connection.commit()
            # Generating rules
            start_time = datetime.now()
            rule_list = generate_rule(frequent_itemsets,support_data,min_confidence)
            # print(rule_list)
            end_time = datetime.now()
            insert_activity_log(self.connection,filter_id,'generate_rules',start_time,end_time)
            insert_rule(self.connection,rule_list)
            self.connection.commit()
            # connection.close()
            self.getLastFilter()
            self.getItemsets()
            self.getRules()
        except Exception as e:
            print(str(e))
            QMessageBox.warning(None,'Recommendation System',str(e))
    @pyqtSlot()
    def filter_itemset_click(self):
        self.getItemsets()
    @pyqtSlot()
    def filter_ant_click(self):
        self.getRules()
    @pyqtSlot()
    def filter_conseq_click(self):
        self.getRules()
Пример #11
0
 def item_list_click(self):
     self.items = ItemList(self.connection)
     self.items.show()
Пример #12
0
 def __init__(self):
     """
     Constructor of libsys class
     """
     self.myitemlist = ItemList()  #list of items
     self.myuserlist = UserList()  #list of users
Пример #13
0
class LibrarySystem:
    """
    Library System Management
    """
    def __init__(self):
        """
        Constructor of libsys class
        """
        self.myitemlist = ItemList()  #list of items
        self.myuserlist = UserList()  #list of users

    def add_new_item(self, item):
        """
        Add item to itemlist.
        :param item: instance of item
        """
        self.myitemlist.add_to_list(item)

    def add_new_user(self, user):
        """
        Add user to user list.
        :param user: instance of user
        """
        self.myuserlist.add_user(user)

    def checkout(self, user, itemid, date=None):
        """
        Accepts user and id of item from input list
        and passes them to user list
        :param user: user
        :param itemid: id of item
        :param date: optional date for the book to be checked out
        :return: user, itemid
        """

        if self.myuserlist.can_borrow(user):
            the_item = self.myitemlist.get_item(itemid)
            self.myuserlist.checkout_item(user, the_item, date)

        # JB here you need to give the user_id to the user_list so they can fin the user & check in the book

        return user, itemid

    def return_item(self, user, itemid):
        """
        Checks in item when returned
        :param user: user
        :param itemid: id of item
        :return: user, itemid
        """

        self.myuserlist.checkin_item(user, itemid)

        # JB here you need to give the user_id to the user_list so they can fin the user & check in the book
        # also might want the option to use a different date so that books can be assigned already overdue (possibly with a default value of datetime.date.today())

        return user, itemid

    def change_fine_of_user(self, user, itemid):
        """
        Checks in item when returned
        :param user: user
        :param itemid: id of item
        :return: user, itemid
        """

        the_item = self.myitemlist.get_item(itemid)

        self.myuserlist.checkin_item(user, the_item)

        # JB here you need to give the user_id to the user_list so they can fin the user & check in the book
        # also might want the option to use a different date so that books can be assigned already overdue (possibly with a default value of datetime.date.today())

        return user, itemid
Пример #14
0
from __future__ import print_function
import sys

from sort_order import SortOrder
from sort_items import SortItems
from item_list import ItemList
from textbox_listener import TextboxListener

print("Running Djinni Python example.")
print("Python version: ", sys.version_info)

test_item_list = ['a', 'z', 'b']
active_items = ItemList(test_item_list)


class MyListener(TextboxListener):
    def update(self, items):
        global active_items
        active_items = items


listener = MyListener()
si = SortItems.create_with_listener(listener)

print("original items: ", active_items.items)
assert active_items.items == test_item_list

si.sort(SortOrder.Ascending, active_items)

print("sorted items: ", active_items.items)
assert active_items.items == sorted(test_item_list)
Пример #15
0
 def __init__(self):
     self.player = Player()
     self.rooms = RoomList()
     self.items = ItemList()
     self.game_map = GameMap()
     self.pawn_shop = PawnShop()