def main():
    # create objects of questions and sections for servey
    qualify1 = Question('1', 'Question 1 text? ', {'a': 'AnswerA', 'b': 'AnswerB', 'c': 'AnswerC'})
    qualify2 = Question('2', 'Question 2 text? ', {'a': 'AnswerA', 'b': 'AnswerB', 'c': 'AnswerC'})
    qualify3 = Question('3', 'Question 3 text? ', {'a': 'AnswerA', 'b': 'AnswerB', 'c': 'AnswerC'})

    q4 = Question('1', 'Question1 Section1 text? ', {'a': 'AnswerA', 'b': 'AnswerB', 'c': 'AnswerC'})
    q5 = Question('2', 'Question2 Section1 text? ', {'a': 'AnswerA', 'b': 'AnswerB', 'c': 'AnswerC'})
    q6 = Question('3', 'Question3 Section1 text? ', {'a': 'AnswerA', 'b': 'AnswerB', 'c': 'AnswerC'})

    q7 = Question('1', 'Question1 Section2 text? ', {'a': 'AnswerA', 'b': 'AnswerB', 'c': 'AnswerC'})
    q8 = Question('2', 'Question2 Section2 text? ', {'a': 'AnswerA', 'b': 'AnswerB', 'c': 'AnswerC'})
    q9 = Question('3', 'Question3 Section2 text? ', {'a': 'AnswerA', 'b': 'AnswerB', 'c': 'AnswerC'})

    q10 = Question('1', 'Question1 Section3 text? ', {'a': 'AnswerA', 'b': 'AnswerB', 'c': 'AnswerC'})
    q11 = Question('2', 'Question2 Section3 text? ', {'a': 'AnswerA', 'b': 'AnswerB', 'c': 'AnswerC'})
    q12 = Question('3', 'Question3 Section3 12 text? ', {'a': 'AnswerA', 'b': 'AnswerB', 'c': 'AnswerC'})

    section_a = Section('SectionA Title', 'Here is some info about what we covered in section_a', [q4, q5, q6], qualify1)
    section_b = Section('SectionB Title', 'Here is some info about what we covered in section_b', [q7, q8, q9], qualify2)
    section_c = Section('SectionC Title', 'Here is some info about what we covered in section_c', [q10, q11, q12], qualify3)
    qualifyquestion = [qualify1, qualify2, qualify3]

    my_survey = Survey('SheCodes Survey', 'This is a placeholder for Description on Survey', qualifyquestion, [section_a, section_b, section_c])
    my_survey.survey_introduction()
Esempio n. 2
0
 def test_complete_task_message(self):
     section = Section("New section")
     task = Task("Tst", "27.04.2020")
     section.add_task(task)
     message = section.complete_task("Tst")
     expected = "Completed task Tst"
     self.assertEqual(message, expected)
Esempio n. 3
0
    def __init__(self, laser, ir, navigator):
        self.laser = laser
        self.ir = ir
        self.navigator = navigator
        self.state = STATE_MEASURING
        self.mapping_state = MAPPING_STATE_FOLLOWING_OUTER_WALL
        self.current_section = Section(NORTH)
        self.saved_sections = []
        self.map_data = [(0, 0)]
        self.current_x = 0
        self.current_y = 0
        self.kitchen_start_x = 0
        self.kitchen_start_y = 0
        self.kitchen_num_mapped = 0
        self.num_kitchen_turns = 0

        self.kitchen_mapping = {}
        self.invalid_kitchens = []
        self.island_data = []
        self.edges_data = []

        self.num_ok_close = 0
        self.num_ok_far = 0

        EventBus.subscribe(CMD_TURN_STARTED, self.on_turning_started)
        EventBus.subscribe(CMD_TURN_FINISHED, self.on_turning_finished)
Esempio n. 4
0
    def __init__(self, name, address, cuisine_type, sections=None, id=DEFAULT_TEST_UUID if DEMO_MODE else None):
        super().__init__(True, id)
        self._json['name'] = name
        self._json['address'] = address
        self._json['cuisineType'] = cuisine_type

        if sections is not None:
            self._json['sections'] = sections
        elif DEMO_MODE:
            print(self.post())
            section = Section('booths', id)
            print(section.post())
            table = Table(3, 25, 25, 0, section.section_id)
            print(table.post())
            reservation = Reservation(table.table_id, id)
            print(reservation.post())
            account = Account()
            print(account.post())
            shift = Shift(None, section.id)
            print(shift.post())
            visit = Visit(shift.id, id)
            print(visit.post())
            order = Order(Status.COOK, 10, account.id,
                          'Steak was undercooked last time.', shift.id, visit.id)
            print(order.post())
            order_two = Order(Status.PREP, 30, account.id,
                              'Less pie flavor please.', shift.id, visit.id)
            print(order_two.post())
Esempio n. 5
0
 def test_add_task_already_added(self):
     section = Section("New section")
     task = Task("Tst", "27.04.2020")
     section.add_task(task)
     message = section.add_task(task)
     expected = "Task is already in the section New section"
     self.assertEqual(message, expected)
Esempio n. 6
0
 def __init__(self, *args, **kwargs):
     Section.__init__(self, *args, **kwargs)
     self._xpath = {}
     self._parent = None
     self._created = datetime.now()
     self._id_string = kwargs.get(u'id_string')
     self._title = kwargs.get(u'title')
     self._print_name = kwargs.get(u'print_name')
     self._def_lang = kwargs.get(u'def_lang')
Esempio n. 7
0
def main():
    parser = build_parser()
    options = parser.parse_args()
    file_parser = FileParser(SECTION_REGEXES, PAPER_REGEXES)
    papers, sections = file_parser.parse_file(OVERVIEW_FILE)

    paper_checks = {
        options.section:
        lambda paper, option: paper.section == Section(option),
        options.papers:
        lambda paper, option: PaperParser.fuzzy_paper_name_match(
            paper.title, option, FUZZY_PAPER_NAME_MATCH_PERCENT),
        options.changed:
        lambda paper, option: paper.changed,
        options.tags:
        lambda paper, option: PaperParser.check_tags(paper.tags, option),
        options.to_read:
        lambda paper, option: not paper.is_read
    }
    papers = PaperParser(paper_checks).parse_papers(papers)

    if not papers:
        print(red("No papers match your search!"))
        return

    if options.download:
        for paper in papers:
            try:
                PaperDownloader.download(paper)
            except KeyboardInterrupt:
                print(red("Stopped download!"))
    elif options.bibtex:
        with open(BIBFILE, 'w') as file:
            for paper in papers:
                print('- {}'.format(paper))
                bibtex = PaperDownloader.get_paper_bibtex(paper)
                if bibtex:
                    file.write(bibtex)
    else:
        if options.section or options.papers or options.changed or options.to_read or options.tags:
            papers_by_section = Section.gather_papers_by_section(papers)
            for section in papers_by_section.keys():
                print('{}\n{}'.format(
                    section, '\n'.join([
                        '- {}'.format(paper)
                        for paper in papers_by_section[section]
                    ])))
        else:
            for section in sections:
                print("{} ({} papers)".format(
                    section, len(section.get_papers_in_section(papers))))

        print("\nTags: [{}]".format(";".join(
            sorted(list(set([tag for paper in papers
                             for tag in paper.tags]))))))
Esempio n. 8
0
    def validate_forms(self):
        """Validate form."""
        root_pass = self.ids.pr2.text
        username = self.ids.us1.text
        user_pass = self.ids.us3.text
        home = self.ids.us4.text
        shell = self.ids.us5.text

        pre = self.ids.pre.text
        pos = self.ids.pos.text

        if self.source:
            s = self.source
        else:
            s = 'cdrom'

        folder = ''
        server = ''
        partition = self.ids.partition.text
        ftp_user = self.ids.ftp_user.text
        ftp_pass = self.ids.ftp_pass.text

        print('SOURCE:' + self.source)
        if s == 'Hard drive':
            folder = self.ids.hh_folder.text
        elif s == 'NFS':
            folder = self.ids.nfs_folder.text
            server = self.ids.nfs_server.text
        elif s == 'HTTP':
            folder = self.ids.http_folder.text
            server = self.ids.http_server.text
        elif s == 'FTP':
            folder = self.ids.ftp_folder.text
            server = self.ids.ftp_server.text

        source = Source()
        source.save_source(s, partition, folder, server, ftp_user, ftp_pass)

        # if self.active is True and self.ids.pr1.text
        # is not self.ids.pr2.text:
        # print(self.ids.pr1.focus)
        # popup = InfoPopup()
        # popup.set_info('Root passwords do not match')
        # popup.open()
        user = User()
        user.save_user(root_pass, username, user_pass, home, shell)
        script = Script()
        script.save_script(pre, pos)
        section = Section()
        section.create_file()
Esempio n. 9
0
    def __init__(self, courseId: str, sectionId: str, termId: str):
        url = getUrl(courseId, sectionId, termId)

        # initialize the values
        self.courseId = courseId
        self.sectionId = sectionId
        self.termId = termId

        # get testudo webpage
        page = requests.get(url)

        # check connectivity
        if page.status_code != 200:
            raise ValueError("Unknown Error - Website Out of Reach")

        # parse the website with BeautifulSoup
        soup = BeautifulSoup(page.text, features='html.parser')

        # locate the part with section infomation
        sectionInfo = soup.find('div', {'class': 'class-days-container'})

        # check if the section/course exists
        sectionList = []
        if sectionInfo is not None:
            # get info for detailed courses
            sections = sectionInfo.findAll('div', {'class': 'row'})

            # process lecture and discussion sections for the course
            for section in sections:
                try:
                    days = section.find('span', {'class': 'section-days'}).string
                    start = section.find('span', {'class': 'class-start-time'}).string
                    end = section.find('span', {'class': 'class-end-time'}).string
                    room = section.find('span', {'class': 'class-room'}).string
                    if "online" not in room.lower():
                        building = section.find('span', {'class': 'building-code'}).string
                    else:
                        building = None
                except AttributeError:
                    days, start, end, building, room = None, None, None, None, None

                # Check for online section
                if start is not None:
                    if section.find('span', {'class': 'class-type'}) is None:
                        sectionList.append(Section(days, start, end, building, room, True))
                    else:
                        sectionList.append(Section(days, start, end, building, room, False))

        self.sectionList = sectionList
Esempio n. 10
0
    def load_sections(self, road_network):
        self.cursor.execute('SELECT * FROM get_section();')
        for (id, name, number_lanes, speed_limit, capacity, from_node_id,
             to_node_id, length) in self.cursor.fetchall():

            if id in road_network.sections:
                raise Error("section id=%d already exists" % id)
            if from_node_id not in road_network.nodes:
                raise Error("section id=%d unknown from-node=%d" %
                            (id, from_node_id))
            if to_node_id not in road_network.nodes:
                raise Error("section id=%d unknown to-node=%d" %
                            (id, to_node_id))

            road_name = name.title()
            if road_name not in road_network.roads:
                road_network.roads[road_name] = Road(road_name)
            road = road_network.roads[road_name]

            from_node = road_network.nodes[from_node_id]
            to_node = road_network.nodes[to_node_id]
            section = Section(id, road, number_lanes, speed_limit, capacity,
                              from_node, to_node, length)
            from_node.add_from_section(section)
            to_node.add_to_section(section)
            road_network.sections[id] = section
            road.sections.append(section)
Esempio n. 11
0
    def parse_file(self, filename):
        with codecs.open(filename, encoding='utf-8', mode='r',
                         buffering=1, errors='strict') as file:

            sections = []
            papers = []
            changed_papers_titles = self.get_changed_papers_titles()
            current_section = None

            for line in file.read().splitlines():
                section_details = FileParser.check_all_regexes(self.section_regexes, line)
                if section_details:
                    section_details_dict = section_details.groupdict()
                    current_section = Section(section_details_dict['name'])
                    sections.append(current_section)
                else:
                    details = FileParser.check_all_regexes(self.paper_regexes, line)
                    if details:
                        paper_details = details.groupdict()
                        paper_title = paper_details['title']
                        papers.append(Paper({
                            'title':      paper_title,
                            'publisher':  paper_details['publisher'],
                            'url':        paper_details['url'],
                            'section':    current_section,
                            'notes_path': paper_details.get('notes_path'),
                            'changed':    paper_title in changed_papers_titles,
                            'is_read':    FileParser.is_read(paper_details['read']),
                            'tags':       paper_details.get('tags')}))

        return papers, sections
Esempio n. 12
0
    def test_all_slots(self):
        lecturer = Lecturer('Benjamin Kommey', 4564541, 'Mr')
        course = Course('Embedded Systems', 'COE 361')

        section = Section('ED CoE', 25, 3,
                          'Electrical and Electronics Engineering',
                          'Computer Engineering')
        c_item = CurriculumItem(section, course, lecturer)

        lecture = Lecture(c_item, 60)

        ttslot = TimetableSlot('Monday', Classroom('LT ', 45, 'PBOO2'),
                               TimeSlot('8:00', '9:00'))
        ttslot1 = TimetableSlot('Tuesday', Classroom(' A110', 300, 'Libary'),
                                TimeSlot('9:00', '10:00'))
        ttslot2 = TimetableSlot('Thursday', Classroom('Room C', 67, 'N1'),
                                TimeSlot('10:00', '11:00'))
        ttslot3 = TimetableSlot('Friday', Classroom('LT ', 45, 'PBOO2'),
                                TimeSlot('11:00', '12:00'))
        ttslot4 = TimetableSlot('Monday', Classroom('LT ', 45, 'PBOO2'),
                                TimeSlot('10:00', '11:00'))

        #print(self.timetable)
        self.assertTrue(self.timetable.add_lecture('Monday', lecture, ttslot))
        self.assertTrue(self.timetable.add_lecture('Tuesday', lecture,
                                                   ttslot1))
        self.assertTrue(
            self.timetable.add_lecture('Thursday', lecture, ttslot2))
        self.assertTrue(self.timetable.add_lecture('Friday', lecture, ttslot3))
        print("############ Testing All Slots##############################")
        slots = self.timetable.all_slots()

        for slot in slots:
            print(slot)
Esempio n. 13
0
    def test_swap_lectures(self):
        pass
        #Test later, not called in generator at the moment
        lecturer = Lecturer('Benjamin Kommey', 4564541, 'Mr')
        course = Course('Embedded Systems', 'COE 361')

        section = Section('ED CoE', 25, 3,
                          'Electrical and Electronics Engineering',
                          'Computer Engineering')
        c_item = CurriculumItem(section, course, lecturer)

        lecture = Lecture(c_item, 60)

        ttslot = TimetableSlot('Monday', Classroom('LT ', 45, 'PBOO2'),
                               TimeSlot('8:00', '9:00'))
        ttslot1 = TimetableSlot('Tuesday', Classroom(' A110', 300, 'Libary'),
                                TimeSlot('9:00', '10:00'))
        ttslot2 = TimetableSlot('Thursday', Classroom('Room C', 67, 'N1'),
                                TimeSlot('10:00', '11:00'))
        ttslot3 = TimetableSlot('Friday', Classroom('LT ', 45, 'PBOO2'),
                                TimeSlot('11:00', '12:00'))
        self.assertTrue(self.timetable.add_lecture('Monday', lecture, ttslot))
        self.assertTrue(self.timetable.add_lecture('Tuesday', lecture,
                                                   ttslot1))
        self.assertTrue(
            self.timetable.add_lecture('Thursday', lecture, ttslot2))
        self.assertTrue(self.timetable.add_lecture('Friday', lecture, ttslot3))
        print(self.timetable)
Esempio n. 14
0
    def sections(self):
        """list[Section]: Loads YAML configuration files and converts them to Section classes. """
        if not self.section_cache:
            # pass each file to the Section class and return the final array
            self.section_cache = [Section(self.load_yaml(self.open_file(f)), self, f) for f in self.splash.sections]

        return self.section_cache
    def __init__(self) -> None:
        """
        Initializes a ClassScheduler object.
        """
        self.var_count = 0
        self.class_ref = {}
        self.section_ref = {}
        self.solver = Glucose3()
        self.going = False

        with open('classes.csv', encoding='utf-8-sig') as classes_file:
            classes_list = [line.split(',') for line in classes_file]
            for class_desc in classes_list:
                class_temp = ClassData(class_desc[0], class_desc[1],
                                       class_desc[2][:-1])
                self.class_ref[class_temp.subject + " " +
                               class_temp.class_id] = class_temp
        with open('sections.csv', encoding='utf-8-sig') as sections_file:
            sections_list = [line.split(',') for line in sections_file]
            for sections_desc in sections_list:
                section_temp = Section(
                    int(sections_desc[0]),
                    sections_desc[2] + " " + sections_desc[1],
                    int(sections_desc[3][:-1]))
                self.section_ref[section_temp.section_id] = section_temp
                self.var_count += 1
        print("Use help() for help operating the scheduler")
Esempio n. 16
0
    def test_room_is_free(self):
        lecturer = Lecturer('Benjamin Kommey',4564541,'Mr')
        course = Course('Embedded Systems','COE 361')

        section = Section('ED CoE',25,3,'Electrical and Electronics Engineering','Computer Engineering')
        c_item = CurriculumItem(section,course,lecturer)

        lecture = Lecture(c_item,60)

        ttslot =  TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('8:00', '9:00'))
        ttslot1 =TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('9:00', '10:00'))
        ttslot2 = TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('10:00', '11:00'))
        ttslot3 = TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('11:00', '12:00'))
        self.assertTrue(self.timetable.add_lecture(lecture,ttslot))
        self.assertTrue(self.timetable.add_lecture(lecture,ttslot1))
        self.assertTrue(self.timetable.add_lecture(lecture,ttslot2))
        self.assertTrue(self.timetable.add_lecture(lecture,ttslot3))
        
        self.assertFalse(self.timetable.room_is_free(Classroom('LT ', 45, 'PBOO2'),TimeSlot('7:00', '8:00')))
        self.assertFalse(self.timetable.room_is_free(Classroom('LT ', 45, 'PBOO2'),TimeSlot('8:00', '9:00')))
        self.assertFalse(self.timetable.room_is_free(Classroom('LT ', 45, 'PBOO2'),TimeSlot('8:00', '9:00')))
        self.assertFalse(self.timetable.room_is_free(Classroom('LT ', 45, 'PBOO2'),TimeSlot('10:00', '11:00')))

        self.assertTrue(self.timetable.room_is_free(Classroom('LT ', 45, 'PBOO2'),TimeSlot('12:00', '13:00')))
        self.assertTrue(self.timetable.room_is_free(Classroom('LT ', 45, 'PBOO2'),TimeSlot('13:00', '14:00')))
        self.assertTrue(self.timetable.room_is_free(Classroom('LT ', 45, 'PBOO2'),TimeSlot('14:00', '15:00')))
        self.assertTrue(self.timetable.room_is_free(Classroom('LT ', 45, 'PBOO2'),TimeSlot('15:00', '16:00')))
Esempio n. 17
0
    def parse_section(self):
        name = strip(self.f.read(16))
        segname = strip(self.f.read(16))
        addr = get_int(self.f) if self.macho.is_32_bit() else get_ll(self.f)
        size = get_int(self.f) if self.macho.is_32_bit() else get_ll(self.f)
        offset = get_int(self.f)
        align = get_int(self.f)
        reloff = get_int(self.f)
        nreloc = get_int(self.f)
        flags = get_int(self.f)
        self.f.read(8) if self.macho.is_32_bit() else self.f.read(12)

        if self.macho.is_little():
            addr = little(addr, 'I') if self.macho.is_32_bit() \
                else little(addr, 'Q')
            size = little(size, 'I') if self.macho.is_32_bit() \
                else little(size, 'Q')
            offset = little(offset, 'I')
            align = little(align, 'I')
            reloff = little(reloff, 'I')
            nreloc = little(nreloc, 'I')
            flags = little(flags, 'I')

        section = Section(name=name,
                          segname=segname,
                          addr=addr,
                          offset=offset,
                          align=align,
                          reloff=reloff,
                          nreloc=nreloc,
                          size=size)
        self.parse_section_flags(section, flags)

        return section
Esempio n. 18
0
    def test_remove_lecture(self):
        #test for removing a lecture from a slot that exists and is occupied
        
        lecturer = Lecturer('Benjamin Kommey',4564541,'Mr')
        course = Course('Embedded Systems','COE 361')

        section = Section('ED CoE',25,3,'Electrical and Electronics Engineering','Computer Engineering')
        c_item = CurriculumItem(section,course,lecturer)

        lecture = Lecture(c_item,60)

        print(self.timetable)
        print('--------TEST - REMOVE-------------------After Adding Lecture-----------------')
        ttslot =  TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('8:00', '9:00'))
        self.assertTrue(self.timetable.add_lecture(lecture,ttslot))
        print(self.timetable)
        self.assertTrue(self.timetable.remove_lecture(ttslot))
        print('-----TEST REMOVE-----------------------After removing Lecture---------------')
        print(self.timetable)

        #test for removing a lecture from a slot that is empty
        self.assertFalse(self.timetable.remove_lecture(ttslot))

        #test for removing a lecture from a slot that does not exists
        self.assertFalse(self.timetable.remove_lecture( TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('7:00', '8:00'))))
Esempio n. 19
0
    def addItem(self, i):
        '''
        Function to add a new section to the wheel

        i: The item title to add to the new section
        '''
        newSection = Section(i, self.center, self.radius, self)
        self.sections.append(newSection)
Esempio n. 20
0
 def __init__(self, c, r, items):
     self.center = c
     self.radius = r
     self.sections = list()
     self.items = items
     for i in self.items:
         newSection = Section(i, self.center, self.radius, self)
         self.sections.append(newSection)
Esempio n. 21
0
 def __init__(self, nodesList, sectionsList):
     """initializing the variables"""
     for tup in nodesList:
         Navigation.nodes.append(Node(tup[0], tup[1], tup[2], tup[3]))
     for tup in sectionsList:
         Navigation.sections.append(
             Section(Navigation.nodes[tup[0]], Navigation.nodes[tup[1]]))
     self.userSpeed = 80
     self.transport = "car"
Esempio n. 22
0
 def get_cantidad(self):
     try:
         text = Section(self.get_text,
                        ('Precio', 1),
                        ('Total:', -1))
         return float(text.reduced_text.split()[0].replace(',', ''))/40
     except Exception as e:
         print(e)
     return None
Esempio n. 23
0
 def get_lote2(self):
     try:
         text = Section(self.get_text,
                        ('Precio', 3),
                        ('Total:', -1))
         return text.reduced_text.split()[-1]
     except Exception as e:
         print(e)
     return None
Esempio n. 24
0
 def xml_instance(self):
     result = Section.xml_instance(self)
     result.setAttribute(u"id", self.id_string)
     
     #We need to add a unique form instance id if the form is to be submitted.
     if self.submission_url:
         result.appendChild(node("orx:meta", node("orx:instanceID")))
         
     return result
Esempio n. 25
0
    def xml_instance(self):
        result = Section.xml_instance(self)
        result.setAttribute(u"id", self.id_string)

        #We need to add a unique form instance id if the form is to be submitted.
        if self.submission_url:
            result.appendChild(node("orx:meta", node("orx:instanceID")))

        return result
Esempio n. 26
0
 def test_clean_section(self):
     section = Section("New section")
     task = Task("Tst", "27.04.2020")
     section.add_task(task)
     section.complete_task("Tst")
     message = section.clean_section()
     expected = "Cleared 1 tasks."
     self.assertEqual(message, expected)
Esempio n. 27
0
File: manager.py Progetto: Rhoana/mb
    def get_meta_info(self, data_path):
        '''
        Get meta information for a requested data path.
        '''

        if data_path not in self._views.keys():

            path_type = self.check_path_type(data_path)

            # detect if this is a section or fov
            if path_type == 'FOV':
                # this is a FoV
                fov = FoV.from_directory(data_path, True)

                view = View.create(
                    data_path,
                    [fov],
                    fov._width,
                    fov._height,
                    fov._tx,
                    fov._ty,
                    self)

            elif path_type == 'SECTION':

                section = Section.from_directory(data_path, True, True)

                view = View.create(
                    data_path,
                    section._fovs,
                    section._width,
                    section._height,
                    section._tx,
                    section._ty,
                    self,
                    section._luts64_map)

            #
            # and add to our views dictionary
            #
            self._views[data_path] = view

        else:

            view = self._views[data_path]

        meta_info = {}
        meta_info['width'] = view._width
        meta_info['height'] = view._height
        meta_info['layer'] = 0
        meta_info['minLevel'] = 0
        meta_info['maxLevel'] = 1
        meta_info['tileSize'] = settings.CLIENT_TILE_SIZE
        meta_info['centers'] = view._centers

        return meta_info
Esempio n. 28
0
 def set_sections_data(self, soup):
     self._sections = []
     count = 0
     while True:
         sect = Section.create(soup, count)
         if sect is not None:
             self._sections.append(sect)
             count += 1
         else:
             break
Esempio n. 29
0
def test_section():
    node1= Node(0,0,0,'first')
    node2= Node(0,1,1,'second')
    node3= Node(1,0,1,'third')
    
    s1=Section(node1,node2)
    s2=Section(node1,node3)
    s1.avgSpeed=50
    s2.avgSpeed=80
    
    assert s1.calcAvgTime(50)==121
    assert s1.calcAvgTime(80)==121
    assert s2.calcAvgTime(50)==121
    assert s2.calcAvgTime(80)==76
    
    s2.n1=node2
    
    assert int(s2.calcAvgTime(50))==170
    assert int(s2.calcAvgTime(80))==107
Esempio n. 30
0
def parse_wrap(nd):
    """This parses one section with class="wrap" (it builds a package) """
    # Title has package name and version
    title = ''
    a = nd.find('.//div/div/div/h2/a')
    if a is None or a.tail is None:
        return

    # Parse the section title
    title = a.tail.strip()
    title = re.sub('\s+', ' ', title)

    # Patch
    title = title.replace('xml::parser', 'xml-parser')

    # Extract build instructions
    snippets = []
    divs = nd.findall('./div')
    with_pkg = False
    sbu = sz = None
    for div in divs:
        # A section may have different (sub-)classes
        if 'class' in div.attrib:
            kl = div.attrib['class']
            if kl == 'package':
                sbu, sz = parse_package(div)
                # print(f'{title}, {sbu} SBU, {sz} GB')
                with_pkg = True
                continue
            # sect2 is used for the 8.4 grub section
            if kl not in ['installation', 'configuration', 'sect2']:
                continue
            for pre in div.findall('.//pre'):
                s = ''
                if pre.text:
                    t = pre.text.strip()
                    s += t
                if 'class' in pre.attrib:
                    kl = pre.attrib['class']
                    # Note: <pre class="root" has only been found in sect1 sections
                    if kl in ['userinput', 'root']:
                        # This is a code snippet
                        kbds = pre.findall('.//kbd[@class="command"]')
                        s += get_kbds_script(kbds)
                        if len(s) > 0:
                            snippets.append(Snippet('userinput', s))
                    elif kl == 'screen':
                        # This is some program output
                        s += get_em_code(pre)
                        if len(s) > 0:
                            snippets.append(Snippet('screen', s))

    # Only create section object if there are instructions
    if len(snippets) > 0:
        return Section(title, snippets, with_pkg=with_pkg, sbu=sbu, sz=sz)
Esempio n. 31
0
    def test_move_lecture(self):
         #test for moving lecture from a slot that is occupied

        #first create a new lecture and then add it to a slot
        lecturer = Lecturer('Benjamin Kommey',4564541,'Mr')
        course = Course('Embedded Systems','COE 361')

        section = Section('ED CoE',25,3,'Electrical and Electronics Engineering','Computer Engineering')
        c_item = CurriculumItem(section,course,lecturer)

        lecture = Lecture(c_item,60)

        print(self.timetable)
        print('---------------------------After Adding Lecture-----------------')
        ttslot =  TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('8:00', '9:00'))
        self.assertTrue(self.timetable.add_lecture(lecture,ttslot))
        print(self.timetable)

         #test for moving lecture from a slot that is not occupied

        self.assertFalse(self.timetable.move_lecture(TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('10:00', '11:00')),
        TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('14:00', '15:00'))))
        print('---------------------After attempting wrong move-------------------')
        print(self.timetable)

         #test for moving lecture to a slot that is not occupied
        self.assertTrue(self.timetable.move_lecture(TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('8:00', '9:00')),
        TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('10:00', '11:00'))
        ))
        print('------------------------------After moving lecture (unoccupied)-------------------------')
        print(self.timetable)
         #test for moving lecture to a slot that is occupied with free as True
        ttslot =  TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('9:00', '10:00'))
        self.assertTrue(self.timetable.add_lecture(lecture,ttslot))
        self.assertFalse(self.timetable.move_lecture(TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('8:00', '9:00')),
        TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('10:00', '11:00'))
        ))
        print(self.timetable)

        #test for moving lecture to a slot that is not occupied with free as False


        #test for moving a lecture back to itself



        #test for moving from a slot that does not exits 
        self.assertFalse(self.timetable.move_lecture(TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('8:00', '10:00')),
        TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('10:00', '11:00'))
        ))

        #test for moving to a slot that does not exits 
        self.assertFalse(self.timetable.move_lecture(TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('8:00', '9:00')),
        TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('10:00', '12:00'))
        ))
Esempio n. 32
0
    def _add_text(
        self, textline
    ):  # saves the content in textline to text as a list of Sections.
        previous_x_max = -1
        min_x = 0
        max_x = 0
        word = ''
        for character in textline:  # iterate through the textline list, every iteration is <text font="Times-Bold" bbox="164.400,546.156,172.324,559.992" colourspace="DeviceGray" ncolour="None" size="13.836">T</text>
            try:  # in case empty text
                coords = character.attrib['bbox'].split(
                    ',')  # get the coordinates
                if previous_x_max == -1:  # if previous_x_max is -1, it means that the current text list is empty
                    previous_x_max = float(coords[2])  # set the previous_x_max
                    min_x = float(coords[0])  # update accordingly
                    max_x = float(coords[2])
                    word += character.text  # add the first character in the word
                    continue  # continue to the next loop since it is the first character in the list

                x_coord_min = float(coords[0])
                x_coord_diff = abs(x_coord_min - previous_x_max)

                if x_coord_diff >= Row.width_diff_tolerance:  # check whether the difference exceeds the tolerance
                    if word != '':  # if the word is not empty, add new Section to the text list
                        self.text.append(Section(min_x, max_x, word))
                    previous_x_max = float(
                        coords[2])  # update the previous_x_max
                    min_x = float(coords[0])
                    max_x = float(coords[2])
                    word = character.text  # update word

                else:
                    word += character.text  # difference less than tolerance means the word hasn't finished yet
                    max_x = float(coords[2])
                    previous_x_max = float(coords[2])
            except:
                pass

        if word != '':  # after iteration add the word in the text list as a Section
            self.text.append(Section(min_x, max_x, word))

        self.text.sort(key=lambda x: x.min_val()
                       )  # sort the text list by the min value of Section
Esempio n. 33
0
    def xml_instance(self):
        result = Section.xml_instance(self)
        result.setAttribute(u"id", self.id_string)

        # add instance xmlns attribute to the instance node
        if self.instance_xmlns:
            result.setAttribute(u"xmlns", self.instance_xmlns)

        if self.version:
            result.setAttribute(constants.VERSION, self.version)
        return result
Esempio n. 34
0
    def xml_instance(self):
        result = Section.xml_instance(self)
        result.setAttribute(u"id", self.id_string)

        #add instance xmlns attribute to the instance node
        if self.instance_xmlns:
            result.setAttribute(u"xmlns", self.instance_xmlns)

        if self.version:
            result.setAttribute(u"version", self.version)
        return result
Esempio n. 35
0
    def update_from_dir(self, directory):
        for p in sorted(pathlib.Path(directory).iterdir()):
            if p.is_file() and p.suffix == '.csv':
                section_name = p.stem
                if not self.get_section(section_name):
                    with p.open() as infile:
                        section = Section.read_csv(infile, name=section_name, quiz=self)

                    yaml_name = p.with_suffix('.yaml')
                    if yaml_name.exists():
                        section.load_answers(yaml_name)
            elif p.is_file() and p.suffixes == ['.csv', '.zip']:
                csv_name = p.stem
                section_name = p.stem.split('.')[0]
                if not self.get_section(section_name):
                    with zipfile.ZipFile(p, 'r') as zipped_file:
                        with io.TextIOWrapper(zipped_file.open(csv_name, 'r')) as infile:
                            section = Section.read_csv(infile, name=section_name, quiz=self)
                    yaml_name = p.parent / (section_name + '.yaml')
                    if yaml_name.exists():
                        section.load_answers(yaml_name)
Esempio n. 36
0
    def xml_instance(self):
        result = Section.xml_instance(self)

        # set these first to prevent overwriting id and version
        for key, value in self.attribute.items():
            result.setAttribute(unicode(key), value)

        result.setAttribute(u"id", self.id_string)

        # add instance xmlns attribute to the instance node
        if self.instance_xmlns:
            result.setAttribute(u"xmlns", self.instance_xmlns)

        if self.version:
            result.setAttribute(u"version", self.version)

        return result
Esempio n. 37
0
  def index(self, input_dir):
    '''
    '''

    json_files = glob.glob(os.path.join(input_dir, '*.json'))

    sections = []

    for json_file in json_files:

      basename = os.path.basename(json_file)

      with open(json_file) as f:
        new_section = Section.fromJSON(json.load(f))
        new_section._id = basename
        new_section._data_prefix = input_dir
        new_section._bbox = View.calculateBB(new_section._tiles)
        sections.append(new_section)

    return sections
Esempio n. 38
0
File: scan.py Progetto: fasrc/mbeam
  def from_directory(directory, calculate_bounding_box=False):
    '''
    Loads a scan from a directory without loading any images.
    '''

    sections = []

    for i,s in enumerate(Util.listdir(directory)):
      section_path = os.path.join(directory, s)

      # if not os.path.isdir(section_path):
      #   # sections always reside in directories
      #   continue

      index_subdirs = i == 0

      section = Section.from_directory(section_path, calculate_bounding_box, index_subdirs)
      sections.append(section)

    scan = Scan(directory, sections)
    
    return scan
def load_student_data(filename):
    """A function that reads data from a CSV file and stores it into objects.

    Args:
       filename: Name of the file

    Returns:
        A dictionary of Grade objects.

    """

    grades_dict = {}

    csv_f = open(filename, 'r')
    i = 0
    for line in csv_f:
        # print "line no:", i, "=", line
        if i > 0:
            # We don't need to read the header, so
            # we do not read line 0
            line_list = []
            line_list = line.split(',')

            grade_number = int(line_list[0])
            # Only create a grade object if it doesn't already exist
            if grade_number in grades_dict:
                grade_temp = grades_dict[grade_number]
            else:
                grade_temp = Grade(grade_number)

            sections_dict = grade_temp.get_sections()
            section_number = int(line_list[1])
            # Only create a section object if it doesn't already exist
            # in that grade
            if section_number in sections_dict:
                section_temp = sections_dict[section_number]
            else:
                section_temp = Section(section_number)

            students_dict = section_temp.get_students()
            student_name = line_list[2]
            # Only create a student object if it doesn't already exist
            # in that section
            if student_name in students_dict:
                student_temp = students_dict[student_name]
            else:
                student_temp = Student(student_name)

            subjects_dict = student_temp.get_subjects()
            subject_name = line_list[3]
            # Only create a subjects object if it doesn't already exist
            # in that student object
            if subject_name in subjects_dict:
                subject_temp = subjects_dict[subject_name]
            else:
                subject_temp = Subject(subject_name)

            tests_dict = subject_temp.get_tests()
            test_obj = Test(line_list[4], int(line_list[5]), int(line_list[6]),
                            line_list[7], line_list[8])

            tests_dict[test_obj.get_test_name()] = test_obj
            subject_temp.set_tests(tests_dict)

            subjects_dict[subject_temp.get_subject_name()] = subject_temp
            student_temp.set_subjects(subjects_dict)

            students_dict[student_temp.get_student_name()] = student_temp
            section_temp.set_students(students_dict)

            sections_dict[section_temp.get_section_number()] = section_temp
            grade_temp.set_sections(sections_dict)

            grades_dict[grade_temp.get_grade_number()] = grade_temp
        # variable i tracks line numbers read
        i = i + 1
    csv_f.close()
    return grades_dict
Esempio n. 40
0
 def reset(cls):
   """Reset to default state."""
   cls.sections_number = 0
   Section.reset()
   return
Esempio n. 41
0
 def __init__(self, *args, **kwargs):
     Section.__init__(self, *args, **kwargs)
     self._xpath = {}
     self._parent = None
     self._created = datetime.now()
Esempio n. 42
0
 def xml_instance(self):
     result = Section.xml_instance(self)
     result.setAttribute(u"id", self.id_string())
     return result
Esempio n. 43
0
 def xml_instance(self):
     result = Section.xml_instance(self)
     result.setAttribute(u"id", self.id_string)
     if self.version:
         result.setAttribute(u"version", self.version)
     return result
Esempio n. 44
0
from user import User
from member import Member
from section import Section
from page import Page
from datetime import datetime
from time import localtime

sections = Section.find()

"""
for section in sections:
    section.attr['create_time'] = datetime.fromtimestamp(section.attr['create_time'])
    section.attr['modified_time'] = datetime.fromtimestamp(section.attr['modified_time'])
    section.commit()
"""

"""
pages = Page.find()
for page in pages:
    page.attr['create_time'] = datetime.fromtimestamp(page.attr['create_time'])
    page.attr['modified_time'] = datetime.fromtimestamp(page.attr['modified_time'])
    page.commit()
"""

a = User()
print (a.attr)
a.set({'email': "*****@*****.**", "username": "******"})
print (a.attr)
Esempio n. 45
0
  def parse(self, config, source):
    """Parse presentation from source stream.

    Parameters
    ----------
    config : MatisseConfig
      MaTiSSe configuration
    source: str
    """
    complete_source = self.parser.includes(source=source)
    self.__get_metadata(source=complete_source)
    self.__get_theme(source=complete_source)
    new_theme = Theme()
    new_theme.set_from(other=self.theme)
    tokens = self.parser.tokenize(source=complete_source)
    self.__check_bad_sectioning(tokens=tokens)
    chapters_number = 0
    sections_number = 0
    subsections_number = 0
    slides_number = 0
    titlepage_inserted = False
    for chap in tokens['chapters']:
      chapters_number += 1
      slide_local_numbers = [0, 0, 0]
      if chap['match'].group('expr'):
        chapter = Chapter(number=chapters_number, title=chap['match'].group('expr'))
      else:
        chapter = Chapter(number=chapters_number, title='')
      for sec in tokens['sections']:
        if sec['start'] >= chap['start'] and sec['start'] <= chap['end_next']:
          sections_number += 1
          slide_local_numbers[1] = 0
          slide_local_numbers[2] = 0
          section = Section(number=sections_number, title=sec['match'].group('expr'))
          for subsec in tokens['subsections']:
            if subsec['start'] >= sec['start'] and subsec['start'] <= sec['end_next']:
              subsections_number += 1
              slide_local_numbers[2] = 0
              subsection = Subsection(number=subsections_number, title=subsec['match'].group('expr'))
              for sld in tokens['slides']:
                if '$titlepage' in sld['match'].group().lower() and not titlepage_inserted:
                  slide = Slide(number=0,
                                title='titlepage',
                                contents=complete_source[sld['end']:sld['end_next']])
                  slide.get_overtheme(parser=self.parser)
                  if slide.overtheme.copy_from_theme is not None and slide.overtheme.copy_from_theme:
                    slide.overtheme.copy_from(other=self.theme)
                  self.position.update_position(presentation_theme=self.theme, overtheme=slide.overtheme)
                  slide.set_position(position=self.position.position)
                  subsection.add_slide(slide=slide)
                  titlepage_inserted = True
                else:
                  if sld['start'] >= subsec['start'] and sld['start'] <= subsec['end_next']:
                    slide_local_numbers[0] += 1
                    slide_local_numbers[1] += 1
                    slide_local_numbers[2] += 1
                    if slide_local_numbers[0] == 1 and config.toc_at_chap_beginning is not None:
                      slides_number += 1
                      self.position.update_position(presentation_theme=self.theme)
                      subsection.add_slide(slide=Slide(number=slides_number,
                                                       position=self.position.position,
                                                       title='Table of Contents',
                                                       contents='$toc[depth:' + str(config.toc_at_chap_beginning) + ']'))
                    if slide_local_numbers[1] == 1 and config.toc_at_sec_beginning is not None:
                      slides_number += 1
                      self.position.update_position(presentation_theme=self.theme)
                      subsection.add_slide(slide=Slide(number=slides_number,
                                                       position=self.position.position,
                                                       title='Table of Contents',
                                                       contents='$toc[depth:' + str(config.toc_at_sec_beginning) + ']'))
                    if slide_local_numbers[2] == 1 and config.toc_at_subsec_beginning is not None:
                      slides_number += 1
                      self.position.update_position(presentation_theme=self.theme)
                      subsection.add_slide(slide=Slide(number=slides_number,
                                                       position=self.position.position,
                                                       title='Table of Contents',
                                                       contents='$toc[depth:' + str(config.toc_at_subsec_beginning) + ']'))
                    slides_number += 1
                    slide = Slide(number=slides_number,
                                  title=sld['match'].group('expr'),
                                  contents=complete_source[sld['end']:sld['end_next']])
                    slide.get_overtheme(parser=self.parser)
                    if slide.overtheme.copy_from_theme is not None and slide.overtheme.copy_from_theme:
                      slide.overtheme.copy_from(other=self.theme)
                    self.position.update_position(presentation_theme=self.theme, overtheme=slide.overtheme)
                    slide.set_position(position=self.position.position)
                    subsection.add_slide(slide=slide)
              section.add_subsection(subsection=subsection)
          chapter.add_section(section=section)
      self.__add_chapter(chapter=chapter)
      self.metadata['total_slides_number'].update_value(value=str(Subsection.slides_number))