Ejemplo n.º 1
0
def pyta_statistics(directory, config=''):
    """
    Recursively run python_ta.check_all() on the files in the directory and its
    subdirectories to collect the error and style messages.
    Assume directory is a folder that contains subdirectories named by
    student's UTORid/studentID/group name, or directory can also be a student
    folder itself. Also assume that student's directory doesn't contain any
    subdirectories, only files.

    @param str directory: The string of the path way of the directory.
    @param str config: A path to the configuration file to use.
    @rtype: dict[str, str]
    """
    all_errors = OrderedDict()

    for root_str, dir_list, file_list in os.walk(directory):
        # check if directory is student directory
        if len(dir_list) == 0:
            student_id = os.path.basename(root_str)

            for file in file_list:
                if file.endswith('.py'):
                    python_ta.check_all(os.path.join(root_str, file),
                                        reporter=StatReporter,
                                        config=config,
                                        number_of_messages=0)
                    # store all the msg objects of this student's files
            all_errors[student_id] = (StatReporter.error_messages,
                                      StatReporter.style_messages)

    if len(all_errors) == 0:
        raise Exception('No student files found in given directory!')
    else:
        _print_stats(*summary(all_errors))
        return all_errors
Ejemplo n.º 2
0
def test_check_on_dir():
    """The function, check_all() should handle a top-level dir as input."""
    _inputs = [
        ['nodes'],
        ['examples']
    ]
    for item in _inputs:
        python_ta.check_all(item, config={'pyta-reporter': 'PlainReporter'})
Ejemplo n.º 3
0
def test_check_on_file():
    """Test files"""
    _inputs = [
        ['nodes/Name.py'],
        ['nodes/Dict.py', 'nodes.Const.py']
    ]
    for item in _inputs:
        python_ta.check_all(item, config={'pyta-reporter': 'PlainReporter'})
Ejemplo n.º 4
0
def test_check_on_bad_input():
    """Test bad inputs. In all cases, pyta should recover.
    Any valid files, if any, should be checked.
    """
    _inputs = [
        [222],
        222,
        ['nodes/Dict.py nodes/Const.py'],
        [222, 'examples/inline_config_comment.py', 'nodes/Dict.py'],
        ['file_does_not_exist']
    ]
    for item in _inputs:
        python_ta.check_all(item, config={'pyta-reporter': 'PlainReporter'})
Ejemplo n.º 5
0
def test_check_with_config():
    """Test inputs along with a config arg."""
    _inputs = [
        ['nodes/Const.py'],
        ['nodes']
    ]
    CONFIG = {
        # [ELIF]
        'max-nested-blocks': 4,
        # [FORMAT]
        'max-line-length': 80,
        # [FORBIDDEN IMPORT]
        'allowed-import-modules': ['doctest', 'unittest', 'hypothesis',
                                   'python_ta'],
        # [FORBIDDEN IO]
        'allowed-io': [],
        # [MESSAGES CONTROL]
        'disable': ['R0401', 'R0901', 'R0903', 'R0904', 'R0911', 'R0916',
                    'W0402', 'W0403', 'W0410', 'W1501', 'W1502', 'W1505',
                    'E1300', 'E1301',  'E1302', 'E1304', 'W1300', 'W1301',
                    'W1302', 'W1304', 'E1124',  'E1125', 'E1129', 'E1132',
                    'W1402', 'W0105', 'E1303', 'W1306',  'W1307', 'E0116',
                    'E0114', 'E0112', 'E0115', 'E0106', 'E0113',  'E0111',
                    'E0105', 'E0100', 'E0117', 'W0150', 'W0120', 'W0124',
                    'W0108', 'W0123', 'W0122', 'W0110', 'C0122', 'C0200',
                    'W0141', 'W0640', 'W0623', 'W0614', 'W0604', 'W0603',
                    'W0602', 'W0601',  'E0604', 'E0603', 'E1200', 'E1201',
                    'E1202', 'W1201', 'E1205',  'E1206', 'similarities',
                    'newstyle', 'python3', 'W0512',  'C0403', 'C0401',
                    'C0402', 'E1701', 'E1700', 'W0332', 'C0327',  'C0328',
                    'E0202', 'E0241', 'E0704', 'W0211', 'W0232', 'W0511',
                    'R0204', 'C0303', 'W0231'],

        # [CUSTOM PYTA OPTIONS]
        'pyta-reporter': 'PlainReporter'
    }
    for item in _inputs:
        python_ta.check_all(item, config=CONFIG)
Ejemplo n.º 6
0
    # still case with special characters.
    lst = filter_string.split(',')
    if len(lst) != 4:
        return False
    for ch in filter_string:
        if ch.isalpha():
            return False
    # now checking if the coordinates are in boundary
    # these are inputed coordinates
    lat1, long1, lat2, long2 = float(lst[0]), float(lst[1]), float(
        lst[2]), float(lst[3])
    if (llc[0] <= long1 <= urc[0]
            and llc[1] <= lat1 <= urc[1]) and (llc[0] <= long2 <= urc[0]
                                               and llc[1] <= lat2 <= urc[1]):
        return True


if __name__ == '__main__':
    import python_ta
    python_ta.check_all(
        config={
            'allowed-import-modules':
            ['python_ta', 'typing', 'time', 'datetime', 'call', 'customer'],
            'max-nested-blocks':
            4,
            'allowed-io': ['apply', '__str__'],
            'disable': ['W0611', 'W0703'],
            'generated-members':
            'pygame.*'
        })
Ejemplo n.º 7
0
    >>> from obfuscated_stack import Stack
    >>> stack = Stack()
    >>> stack.push(1)
    >>> stack.push(2)
    >>> reverse_top_two(stack)
    >>> stack.pop()
    1
    >>> stack.pop()
    2
    """
    # TODO: implement this function after you've read about Stacks.
    new_second = stack.pop()
    new_first = stack.pop()
    stack.push(new_second)
    stack.push(new_first)


if __name__ == '__main__':
    import doctest
    doctest.testmod()

    # Uncomment and run before final submission. This checks for style errors
    # in addition to code inconsistencies and forbidden Python features.
    import python_ta
    python_ta.check_all(config={
        'allowed-import-modules': [
            'doctest', 'python_ta', 'typing',
            'math', 'random', 'obfuscated_stack'
        ]
    })
Ejemplo n.º 8
0
    # if remove_student() removes an enrolled student, add in the first
    # waitlisted student to enrolled students.
    # HINT: The list method .pop() might be useful here.
    #       See help(list.pop) for details.
    c.remove_student("Danny")
    assert c.get_enrolled_students() == ['Jacqueline', 'Sophia']
    assert c.get_waitlist() == ['David']

    c.remove_student("David")
    assert c.get_waitlist() == []

    # When comparing 2 courses, they are the same if the enrolled students
    # are the same (regardless of order), the waitlist is the same
    # (and in the same order), and the course code and capacity are the same.
    c2 = Course("CSC148")
    c2.set_course_capacity(2)
    c2.add_student("Jacqueline")
    c2.add_student("Sophia")
    assert c == c2

    c2.add_student("David")
    assert c != c2

    # Below is how python_ta (PythonTA/pyTA/etc.) is called.
    # When run, your code should produce no errors from python_ta.
    # You must have python_ta installed for this to work (see Lab 1 and
    # the Software Installation page).
    import python_ta

    python_ta.check_all(config="ex1_pyta.txt")
Ejemplo n.º 9
0
    ghg_train, ghg_test, gdp_train, gdp_test = train_test_split(ghg1,
                                                                gdp1,
                                                                test_size=0.2)

    # train the model
    ghg_model = l_reg.fit(ghg_train, gdp_train)

    # Print relevant text output
    regression2_text_info(ghg_train, ghg_test, gdp_train, gdp_test)

    import python_ta

    python_ta.check_all(
        config={
            'extra-imports': [
                'math', 'sklearn', 'sklearn.model_selection', 'numpy',
                'pandas', 'plotly', 'plotly.express', 'python_ta.contracts'
            ],
            'allowed-io': ['regression2_text_info', 'regression1_text_info'],
            'max-line-length':
            100,
            'disable': ['R1705', 'C0200']
        })

    import python_ta.contracts
    python_ta.contracts.DEBUG_CONTRACTS = False
    python_ta.contracts.check_all_contracts()

    import doctest
    doctest.testmod()
        1
        >>> j = StoneHengeState(True, [{'I': [1, 1, 'B'], \
        'II': ['@', 'C']}, \
        {'I': [1, 1, 'C'], \
        'II': ['@', 'B']}, \
        {'I': [1, 1], \
        'II': ['@', 'B', 'C']}])
        >>> j.rough_outcome()
        -1
        """

        x = [self.make_move(move) for move in self.get_possible_moves()]
        if any([j.get_possible_moves() == [] for j in x]):
            return self.WIN

        checker = []
        for state in x:
            new_state = [
                state.make_move(moves) for moves in state.get_possible_moves()
            ]
            if any([k.get_possible_moves() == [] for k in new_state]):
                checker.append('OK')
        if checker.count('OK') == len(x):
            return self.LOSE
        return self.DRAW


if __name__ == "__main__":
    from python_ta import check_all
    check_all(config="a2_pyta.txt")
Ejemplo n.º 11
0
                for n in neighbourhood
            ])
            ratings_list = ratings_list[:self._max_neighbours]

            total_score, total_sim = 0, 0
            for sim, an in ratings_list:
                review = self.graph.get_weight(user, an)
                total_score += sim * review
                total_sim += sim

            if total_sim == 0:
                return round(self.graph.average_weight(anime))
            else:
                return round(total_score / total_sim)


if __name__ == '__main__':
    import python_ta.contracts
    python_ta.contracts.check_all_contracts()

    import doctest
    doctest.testmod()

    import python_ta
    python_ta.check_all(
        config={
            'max-line-length': 100,
            'disable': ['E1136'],
            'extra-imports': ['recommendations']
        })
Ejemplo n.º 12
0
            return items

    def levels(self) -> List[Tuple[int, list]]:
        """Return a list of items in the tree, separated by level.

        You may wish to use 'items_at_depth' as a helper method,
        but this also makes your code less efficient. Try doing
        this method twice, once with 'items_at_depth', and once
        without it!
        """
        if self.is_empty():
            return []
        result, current = [], [self]
        d = 1
        while current:
            next_level, vals = [], []
            for tree in current:
                vals.append(tree._root)
                if not tree._left.is_empty():
                    next_level.append(tree._left)
                if not tree._right.is_empty():
                    next_level.append(tree._right)
            current = next_level
            result.append((d, vals))
            d += 1
        return result

if __name__ == '__main__':
    import python_ta
    python_ta.check_all()
Ejemplo n.º 13
0
    the maximum # of affected in DATASET1.csv is 134000000.

    Resulting value is 0 to 1, inclusive.

    Preconditions:
        - 0 <= deaths <= maximum
        - maximum in [222570, 134000000]
    """
    return number / maximum


if __name__ == '__main__':
    import python_ta

    python_ta.check_all(
        config={
            'extra-imports': ['python_ta.contracts', 'csv'],
            'max-line-length': 200,
            'allowed-io': ['read_csv'],
            'disable': ['R1705', 'C0200']
        })

    import python_ta.contracts

    python_ta.contracts.DEBUG_CONTRACTS = False
    python_ta.contracts.check_all_contracts()

    import doctest

    doctest.testmod(verbose=True)
            book_review = int(row[2])
            graph.add_vertex(user_name, 'user')
            graph.add_vertex(dict_of_books[user_book_num], 'book')

            curr_book = dict_of_books[user_book_num]
            if user_book_num in dict_of_books:
                graph.add_edge(user_name, curr_book, book_review)
    return graph


if __name__ == '__main__':
    # You can uncomment the following lines for code checking/debugging purposes.
    # However, we recommend commenting out these lines when working with the large
    # datasets, as checking representation invariants and preconditions greatly
    # increases the running time of the functions/methods.
    # import python_ta.contracts
    # python_ta.contracts.check_all_contracts()

    import doctest
    doctest.testmod()

    import python_ta
    python_ta.check_all(
        config={
            'max-line-length': 1000,
            'disable': ['E1136', 'W0221'],
            'extra-imports': ['csv', 'a3_part1'],
            'allowed-io': ['load_weighted_review_graph'],
            'max-nested-blocks': 4
        })
Ejemplo n.º 15
0
        __preorder_pls(tree.left, freq_dict, ff)
        __preorder_pls(tree.right, freq_dict, ff)


if __name__ == "__main__":
    import doctest

    doctest.testmod()

    import python_ta

    python_ta.check_all(
        config={
            'allowed-io': ['compress_file', 'decompress_file'],
            'allowed-import-modules': [
                'python_ta', 'doctest', 'typing', '__future__', 'time',
                'utils', 'huffman', 'random'
            ],
            'disable': ['W0401']
        })

    mode = input(
        "Press c to compress, d to decompress, or other key to exit: ")
    if mode == "c":
        fname = input("File to compress: ")
        start = time.time()
        compress_file(fname, fname + ".huf")
        # cProfile.run('compress_file(fname, fname + ".huf")')
        print("Compressed {} in {} seconds.".format(fname,
                                                    time.time() - start))
    elif mode == "d":
Ejemplo n.º 16
0
        >>> my_corp = Company([\
        SalariedEmployee(24, 'Gilbert the cat', 1200.0), \
        HourlyEmployee(25, 'Chairman Meow', 500.25, 1.0)])
        >>> my_corp.pay_all(date(2018, 6, 28))
        An employee was paid 100.0 on 2018-06-28.
        An employee was paid 500.25 on 2018-06-28.
        >>> my_corp.total_payroll()
        600.25
        """
        x = 0.0
        for i in self.employees:
            x += i.total_pay()
        return x

if __name__ == '__main__':
    import doctest
    doctest.testmod()

    # Remember: you'll need to *run this file* to actually get the lines below
    # to run. This is different than just running doctests.
    # To run this file in PyCharm, right-click in the file and select
    # "Run...", and then select "prep3" from the menu that appears.
    # DON'T select "Doctests in prep3", as that command will not actually
    # run this file, but instead only run its doctests.
    import python_ta
    python_ta.check_all(config={
        'extra-imports': ['datetime'],
        'allowed-io': ['pay']
    })
Ejemplo n.º 17
0

def _build_tree_from_dict(nested_dict: Dict) -> List[PaperTree]:
    """Return a list of trees from the nested dictionary <nested_dict>.
    """
    ans = []
    if nested_dict == {}:
        return ans

    elif 'authors' in nested_dict.keys():
        ans.append(
            PaperTree(nested_dict['name'], [], nested_dict['authors'],
                      nested_dict['doi'], nested_dict['citations']))

    else:
        for name, yep in nested_dict.items():
            ans.append(PaperTree(name, _build_tree_from_dict(yep)))

    return ans


if __name__ == '__main__':
    import python_ta
    python_ta.check_all(
        config={
            'allowed-import-modules':
            ['python_ta', 'typing', 'csv', 'tm_trees'],
            'allowed-io': ['_load_papers_to_dict'],
            'max-args': 8
        })
Ejemplo n.º 18
0
        """ Return a bill summary for the <month>+<year> billing cycle, as a
        dictionary.
        This dictionary will include the following string keys:
        "number" - indicates the phone number
        "type" - indicates the contract type
        "fixed" - fixed cost for that month
        "free_mins" - number of free minutes used in this monthly cycle
        "billed_mins" - number of billed minutes used in this monthly cycle
        "min_rate" - billing rate per minute
        "total" - total cost for this monthly bill
        The values corresponding to each key represent the respective amounts.
        If no bill exists for this month+year, return None.
        """
        if (month, year) not in self.bills:
            return None

        bill_summary = self.bills[(month, year)].get_summary()
        bill_summary['number'] = self.number
        return bill_summary


if __name__ == '__main__':
    import python_ta
    python_ta.check_all(
        config={
            'allowed-import-modules':
            ['python_ta', 'typing', 'call', 'callhistory', 'bill', 'contract'],
            'generated-members':
            'pygame.*'
        })
Ejemplo n.º 19
0
    stack_help = Stack()
    while not queue.is_empty():
        stack_help.push(queue.dequeue())
    queue.enqueue(stack_help.pop())


class EmptyPopError(Exception):
    pass


class EmptyPopErrorDoc(Exception):
    def __str__(self):
        return 'You cannot pop from empty list'


if __name__ == '__main__':
    import doctest
    doctest.testmod()

    # Remember, to get this to work you need to Run this file, not just the
    # doctests in this file!
    import python_ta
    python_ta.check_all(config={
        'extra-imports': ['adts']
    })





Ejemplo n.º 20
0
        """
        monthly_history = ([], [])
        if month is not None and year is not None:
            if (month, year) in self.outgoing_calls:
                for call in self.outgoing_calls[(month, year)]:
                    monthly_history[0].append(call)

            if (month, year) in self.incoming_calls:
                for call in self.incoming_calls[(month, year)]:
                    monthly_history[1].append(call)
        else:
            for entry in self.outgoing_calls:
                for call in self.outgoing_calls[entry]:
                    monthly_history[0].append(call)
            for entry in self.incoming_calls:
                for call in self.incoming_calls[entry]:
                    monthly_history[1].append(call)
        return monthly_history


if __name__ == '__main__':
    import python_ta
    python_ta.check_all(config={
        'allowed-import-modules': [
            'python_ta', 'typing', 'datetime', 'call'
            ''
        ],
        'disable': ['R0902', 'R0913'],
        'generated-members': 'pygame.*'
    })
Ejemplo n.º 21
0
    p2 = make_player('p2')
    while True:
        g = NumberGame(goal, minimum, maximum, (p1, p2))
        winner = g.play()
        print(f'And {winner} is the winner!!!')
        print(p1)
        print(p2)
        again = input('Again? (y/n) ')
        if again != 'y':
            return


if __name__ == '__main__':
    # Uncomment the lines below to check your work using
    # python_ta and doctest.
    import python_ta
    python_ta.check_all(config={
        'extra-imports': ['random'],
        'allowed-io': [
            'main',
            'make_player',
            'move',
            'play_one_turn'
        ]
    })
    # import doctest
    # doctest.testmod()

    # Uncomment the following line to run the number game.
    # main()
Ejemplo n.º 22
0
        If a UI element with the certain label does not exist, raise NameError
        """

        if label not in self._ui_elements:
            raise NameError
        else:
            return self._ui_elements[label]


if __name__ == '__main__':
    import python_ta

    python_ta.check_all(config={
        'extra-imports': ['pygame', 'pygame_gui', 'pygame_gui.elements.ui_horizontal_slider',
                          'typing', 'button', 'python_ta.contracts'],
        # the names (strs) of imported modules
        'allowed-io': [],
        # the names (strs) of functions that call print/open/input
        'max-line-length': 100,
        'disable': ['R1705', 'C0200']
    })

    import python_ta.contracts
    python_ta.contracts.check_all_contracts()

    import doctest

    doctest.testmod()

Ejemplo n.º 23
0
        # Sort the list based on the distance (minimum)
        dist_so_far.sort(key=lambda x: x[1])

        return [dist_so_far[i][0] for i in range(3)]

    def get_location(self, name: str) -> tuple:
        """Return the location attribute of the given vertex

        Preconditions:
            - name in self._vertices
        """
        return self._vertices[name].location


if __name__ == '__main__':
    import python_ta

    python_ta.check_all(
        config={
            'max-line-length': 100,
            'extra-imports': ['python_ta.contracts', 'typing', 'distance'],
            'disable': ['E1136', 'W0221']
        })
    import python_ta.contracts

    python_ta.contracts.DEBUG_CONTRACTS = False
    python_ta.contracts.check_all_contracts()
    import doctest

    doctest.testmod()
Ejemplo n.º 24
0
    def add_group(self, group: Group) -> bool:
        """
        Add <group> to this grouping and return True.

        Iff adding <group> to this grouping would violate a representation
        invariant don't add it and return False instead.
        """
        if group.__len__() == 0:
            return False
        sts = group.get_members()
        for st in sts:
            for exist_group in self._groups:
                if st in exist_group:
                    return False
        self._groups.append(group)
        return True

    def get_groups(self) -> List[Group]:
        """ Return a list of all groups in this grouping.
        This list should be a shallow copy of the self._groups
        attribute.
        """
        copy = self._groups[:]
        return copy


if __name__ == '__main__':
    import python_ta
    python_ta.check_all(
        config={'extra-imports': ['typing', 'random', 'survey', 'course']})
Ejemplo n.º 25
0
import sys
sys.path.insert(0, 'pyta')

print("================= Start: checking coding style =================")

import python_ta
python_ta.check_all('admission_functions.py', config='pyta/a1_pyta.txt')

print("================= End: checking coding style =================\n")

print(
    "================= Start: checking parameter and return types ================="
)

import builtins

# Check for use of functions print and input.

# IMPORTANT!
# If you are getting a syntax error here for the line:
#     our_print = print
# Then you are using the wrong version of Python!
our_print = print
our_input = input


def disable_print(*args):
    raise Exception("You must not call print anywhere in your code!")


def disable_input(*args):
Ejemplo n.º 26
0
        Goal's target colour, (b) includes the cell at <pos>, and (c) involves
        only cells that have never been visited.

        If <pos> is out of bounds for <board>, return 0.

        <board> is the flattened board on which to search for the blob.
        <visited> is a parallel structure that, in each cell, contains:
           -1  if this cell has never been visited
            0  if this cell has been visited and discovered
               not to be of the target colour
            1  if this cell has been visited and discovered
               to be of the target colour

        Update <visited> so that all cells that are visited are marked with
        either 0 or 1.
        """
        pass


if __name__ == '__main__':
    import python_ta
    python_ta.check_all(
        config={
            'allowed-import-modules': [
                'doctest', 'python_ta', 'random', 'typing', 'block', 'goal',
                'player', 'renderer'
            ],
            'max-attributes':
            15
        })
Ejemplo n.º 27
0

def run_treemap_papers() -> None:
    """Run a treemap visualization for CS Education research papers data.

    You can try changing the value of the named argument by_year, but the
    others should stay the same.
    """
    paper_tree = PaperTree('CS1', [], all_papers=True, by_year=False)
    run_visualisation(paper_tree)


if __name__ == '__main__':
    import python_ta
    python_ta.check_all(config={
        'allowed-import-modules': [
            'python_ta', 'typing', 'pygame', 'tm_trees', 'papers'
        ],
        'generated-members': 'pygame.*'
    })

    # To check your work for Tasks 1-5, try uncommenting the following function
    # call, with the '' replaced by a path like
    # 'C:\\Users\\David\\Documents\\csc148\\assignments' (Windows) or
    # '/Users/dianeh/Documents/courses/csc148/assignments' (OSX)
    #run_treemap_file_system('C:\\Users\\svato\\Desktop\\first year\\csc1481111\\csc148\\assignments\\a2\\example-directory\\')

    # To check your work for Task 6, try uncommenting the following
    run_treemap_papers()

Ejemplo n.º 28
0
    return emissions_so_far


def calculate_coeff(x_value: float, m_value: float, b_value: float) -> float:
    """Calculate the y-value in the linear regression equation, y = mx + b
    using the given coefficients.
    """
    return (m_value * x_value) + b_value


if __name__ == '__main__':
    import python_ta

    python_ta.check_all(config={
        'max-line-length': 120,
        'extra-imports': ['python_ta.contracts', 'pandas', 'plotly.express', 'data_processing', 'sklearn.svm',
                          'plotly.graph_objects', 'numpy', 'List'],
        'disable': ['R1705', 'C0200'],
        'allowed-io': ['nuclear_position_map']
    })

    import python_ta.contracts

    python_ta.contracts.DEBUG_CONTRACTS = False
    python_ta.contracts.check_all_contracts()

    import doctest

    doctest.testmod()
Ejemplo n.º 29
0
            - Level 2: waiting 5-6 rounds
            - Level 3: waiting 7-8 rounds
            - Level 4: waiting >= 9 rounds
        """
        anger_level = None

        if self.wait_time <= 2:
            anger_level = 0
        elif 3 <= self.wait_time <= 4:
            anger_level = 1
        elif 5 <= self.wait_time <= 6:
            anger_level = 2
        elif 7 <= self.wait_time <= 8:
            anger_level = 3
        elif self.wait_time >= 9:
            anger_level = 4

        return anger_level


if __name__ == '__main__':
    import python_ta

    python_ta.check_all(
        config={
            'extra-imports': ['sprites'],
            'max-nested-blocks': 4,
            'max-attributes': 12,
            'disable': ['R0201']
        })
Ejemplo n.º 30
0
        original_score = self.goal.score(board)
        optimal_score = 0
        optimal_move = None
        for _ in range(self.difficulty):
            copy = board.create_copy()
            x = _valid_move(self, board, copy)
            score = self.goal.score(copy)
            if score > optimal_score:
                optimal_score = score
                optimal_move = x

        self._proceed = False  # Must set to False before returning!
        if original_score >= optimal_score:
            return _create_move(PASS, board)
        return optimal_move


if __name__ == '__main__':
    import python_ta

    python_ta.check_all(config={
        'allowed-io': ['process_event'],
        'allowed-import-modules': [
            'doctest', 'python_ta', 'random', 'typing', 'actions', 'block',
            'goal', 'pygame', '__future__'
        ],
        'max-attributes': 10,
        'generated-members': 'pygame.*'
    })
Ejemplo n.º 31
0
    while path_via[curr]:
        path.insert(0, path_via[curr])
        curr = path_via[curr]
    if start_vertex not in path:
        raise NoShortestPathError
    else:
        return path


if __name__ == '__main__':
    import python_ta

    python_ta.check_all(
        config={
            'max-line-length':
            100,
            'extra-imports':
            ['python_ta.contracts', 'typing', 'math', 'map_graph', 'heapq'],
            'disable': ['R1705', 'C0200']
        })
    import python_ta.contracts

    python_ta.contracts.DEBUG_CONTRACTS = False
    python_ta.contracts.check_all_contracts()
    import doctest

    doctest.testmod()
    import pytest
    pytest.main(['dijkstra.py'])
Ejemplo n.º 32
0
        surface.blit(text_surface, self._iteration_text_pos)

    def _draw_timer(self, clock: Timer, surface: pygame.Surface) -> None:
        text_surface = clock.get_text_surface()
        surface.blit(self._timer_text_background, self._timer_text_pos)
        surface.blit(text_surface, self._timer_text_pos)


def _get_text_surface(longest_text: str) -> pygame.Surface:
    """
    Return a white box that is the size of the maximum possible text being rendered
    """
    text_surface = pygame.font.SysFont('Arial', 20).render(longest_text, True, (0, 0, 0))
    text_h = text_surface.get_height()
    text_w = text_surface.get_width()
    white = pygame.Surface((text_w, text_h))
    white.fill((255, 255, 255))
    return white


if __name__ == '__main__':
    import python_ta
    import python_ta.contracts
    python_ta.contracts.check_all_contracts()
    python_ta.check_all(config={
        'extra-imports': ['pygame', 'matrix_graph', 'typing', 'clock', 'queue'],
        'allowed-io': [],  # the names (strs) of functions that call print/open/input
        'max-line-length': 100,
        'disable': ['E1136']
    })
Ejemplo n.º 33
0
        Precondition: force >= 0.

        Hint: use the "%" operator to "wrap around" the spinner's position.
        """
        self.position = (self.position + force) % self.size

    def spin_randomly(self) -> None:
        """Spin this spinner randomly.

        This modifies the spinner's arrow to point to a random slot on the
        spinner. Each slot has an equal chance of being pointed to.

        You MUST use randint (imported from random) for this method, to
        choose a random slot.
        """
        num = randint(0, self.size)
        self.spin(num)


if __name__ == '__main__':
    # When you run the module, you'll both run doctest and python_ta
    # to check your work.
    import doctest
    doctest.testmod()

    # python_ta opens up your web browser to display its report.
    # You want to see "None!" under both "Code Errors" and
    # "Style and Convention Errors" for full marks.
    import python_ta
    python_ta.check_all(config={'extra-imports': ['random']})
Ejemplo n.º 34
0
"""Checker for CSC108 Assignment 3"""

import sys

sys.path.insert(0, './pyta')


print("================= Start: checking coding style =================")

import python_ta
python_ta.check_all('network_functions.py', config='pyta/a3_pyta.txt')

print("================= End: checking coding style =================\n")


print("================= Start: checking parameter and return types =================")

import builtins
import io
import copy
import network_functions as nf # imported here so code that doesn't import correctly gets style checked


# Check for use of functions print and input.
our_print = print
our_input = input

def disable_print(*_args, **_kwargs):
    """ Notices if print is called """
    raise Exception("You must not call built-in function print!")
Ejemplo n.º 35
0
        """ Return a score for <grouping> calculated based on the answers of
        each student in each group in <grouping> to the questions in <self>.

        If there are no groups in <grouping> this score is 0.0. Otherwise, this
        score is determined using the following algorithm:

        1. For each group in <grouping>, get the score for the members of this
           group calculated based on their answers to the questions in this
           survey.
        2. Return the average of all the scores calculated in step 1.

        === Precondition ===
        All students in the groups in <grouping> have an answer to all questions
            in this survey
        """
        score = 0
        count = 0
        for group in grouping.get_groups():
            score += self.score_students(group.get_members())
            count += 1

        return score / count


if __name__ == '__main__':
    import python_ta
    python_ta.check_all(config={'extra-imports': ['typing',
                                                  'criterion',
                                                  'course',
                                                  'grouper']})
Ejemplo n.º 36
0
        less from the boat, else return None
        @type s_range: int
        @rtype: Node, None
        """
        # TODO
        pass

    def plot_path(self, start_node, target_node):
        """
        Return a string representation of the grid map,
        plotting the shortest path from start_node to target_node
        computed by find_path using "*" characters to show the path
        @type self: Grid
        @type start_node: Node
        @type target_node: Node
        @rtype: str
        >>> g = Grid("", ["B.++", ".+..", "...T"])
        >>> print(g.plot_path(g.boat, g.treasure))
        B*++
        .+*.
        ...T
        """
        # TODO
        pass

if __name__ == '__main__':
    # import doctest
    # doctest.testmod()
    import python_ta
    python_ta.check_all(config='pylintrc.txt')
Ejemplo n.º 37
0
        """
        return caster.get_hp() > 50

    def no_condition(_, __):
        """
        By default, return True.
        """
        return True

    priority_1 = SkillDecisionTree(RogueAttack(), caster_hp_gt_90, 1)
    priority_2 = SkillDecisionTree(MageSpecial(), target_sp_gt_40, 2)
    priority_3 = SkillDecisionTree(MageAttack(), caster_sp_gt_20, 3)
    priority_4 = SkillDecisionTree(RogueSpecial(), target_hp_lt_30, 4)
    priority_5 = SkillDecisionTree(MageAttack(), caster_hp_gt_50, 5)
    priority_6 = SkillDecisionTree(RogueAttack(), no_condition, 6)
    priority_7 = SkillDecisionTree(RogueSpecial(), no_condition, 7)
    priority_8 = SkillDecisionTree(RogueAttack(), no_condition, 8)

    priority_4.children.append(priority_6)
    priority_3.children.append(priority_4)
    priority_2.children.append(priority_8)
    priority_1.children.append(priority_7)

    priority_5.children = [priority_3, priority_2, priority_1]
    return priority_5


if __name__ == '__main__':
    import python_ta
    python_ta.check_all(config='a2_pyta.txt')