Esempio n. 1
0
    def __init__(self):
        self.startCalc = -400
        self.startAddData = -400
        self.startUpdateWallet = -3
        self.parser_ = Parser()

        # === Update model === #
        self.updateModel_ = False
        self.reDoModel_ = False
        # ==================== #

        # TODO Implémenter ça depuis les données envoyées
        self.trainPair_ = ('USDT', 'ETH')
        self.strategy_ = Strategy(trainPair=self.trainPair_, updateModel=self.updateModel_)
        self.reference_ = 'USDT'
        self.wallet_ = Wallet(None, self.reference_)

        self.reDoModel_ = self.updateModel_ if self.updateModel_ is False else self.reDoModel_
        if self.reDoModel_ is True:
            self.strategy_.removeTrainedModel()

        # === CONSTANT === #
        self.save_ = os.dup(1)
        self.trainTime_ = True
        self.startIter = None
        self.currentIter = 0
        self.saveStdout = os.dup(1)
        os.dup2(2, 1)
Esempio n. 2
0
def runmain():
    from src.Semantic_Analyzer import SemanticAnalyzer
    from src.Parser import Parser

    while True:
        try:
            text = \
                """PROGRAM Test;
                   VAR
                       a : INTEGER;
                   BEGIN
                       a := 1
                   END.
                """            
            #input('calc> ')
        except EOFError:
            break
        if not text:
            continue

        lexer = Lexer(text)
        parser = Parser(lexer)
        tree = parser.parse()

        semantic_analyzer = SemanticAnalyzer()
        
        try:
            semantic_analyzer.visit(tree)
        except SystemError as sys_error:
            print(sys_error)

        for token in lexer.tokens:
            print(token)

        break
def testMarkdownTags():
    def nbFilesWithTag(parser, tag):
        return len([file for file in parser.mdFiles if tag in file.tags])

    parser = Parser('./test/testVault')
    for tag in ['tag2', 'tag1', 'inexistent']:
        files = parser.searchFilesWithTag(tag)
        assert len(files) == nbFilesWithTag(parser, tag)
def main():
    parser = Parser()
    args = parser.get_parsed_args()
    ip_parser = IP_Parser()
    node_ip = ip_parser.parse(args.ip)
    peer_search = Peer_search()
    peer_search.init(Network_utils.get_udp_socket(node_ip.ip, int(node_ip.port)))
    peer_search.join_network(args.bootstrap)
    peer_search.search(["reddit"]) # needs to be a list
    peer_search.search(["hackernews"]) # needs to be a list
Esempio n. 5
0
 def makeInterpreter(self, text):
     from src.Lexer import Lexer
     from src.Parser import Parser
     from src.Interpreter import Interpreter
     from src.SymbolTable import SymbolTableBuilder
     lexer = Lexer(text)
     parser = Parser(lexer)
     tree = parser.parse()
     symtab_builder = SymbolTableBuilder()
     symtab_builder.visit(tree)
     interpreter = Interpreter(tree)
     return interpreter
Esempio n. 6
0
def main():
    parser = Parser()
    args = parser.get_parsed_args()
    ip_parser = IP_Parser()
    node_ip = ip_parser.parse(args.ip)
    peer_search = Peer_search()
    peer_search.init(Network_utils.get_udp_socket(node_ip.ip, int(node_ip.port)))
    peer_search.join_network(args.bootstrap)
    peer_search.index_page("reddit.com", ["reddit", "frontpage", "of", "the", "internet"])
    peer_search.index_page("reddit.com", ["reddit", "cats", "lots", "of", "cats"])
    peer_search.index_page("reddit.com", ["reddit", "hackernews", "internet", "of", "cats"])
    peer_search.index_page("news.ycombinator.com", ["reddit", "hackernews", "internet", "of", "cats"])
    peer_search.index_page("google.com", ["reddit", "frontpage", "of", "the", "internet"])
Esempio n. 7
0
def test_write_output_file(parsed_data, delimiter_symbol, output_file,
                           output_format, expected_file):
    outputted_file = open(output_file, "w")

    parser = Parser()

    parser.write_output_file(parsed_data, delimiter_symbol, outputted_file,
                             output_format)

    res_file = open(output_file, 'r')
    exp_file = open(expected_file, 'r')

    assert res_file.read() == exp_file.read()
Esempio n. 8
0
def main(argv=sys.argv):
    parser = Parser()

    # Generate training data
    lexStr = parser.getLexFromXML("../docs/samePopularnonaukowe/uczace/")
    result = parser.parseLex(lexStr)
    parser.printToFile("../docs/samePopularnonaukowe/parsingOutput/train.data",
                       result)

    #lexStr = parser.xxx("../docs/samePopularnonaukowe/uczace/")
    #parser.printToFile("../docs/samePopularnonaukowe/parsingOutput/train.data", lexStr)
    # Generate testing data
    lexStr = parser.getLexFromXML("../docs/samePopularnonaukowe/testowe/kap")
    result = parser.parseLex(lexStr)
    parser.printToFile("../docs/samePopularnonaukowe/parsingOutput/test.data",
                       result)
Esempio n. 9
0
def test_infinitive_solutions1():
    equation = "5 * X^2 = 5 * X^2"
    try:
        parser = Parser(equation)
        polynom = Polynom(parser)
    except:
        pass
Esempio n. 10
0
def test_big_degree1():
    equation = "4 * X^0 + 4 * X^1 - 9.3 * X^2 = 1 * X^3"
    try:
        parser = Parser(equation)
        Polynom(parser)
    except:
        pass
Esempio n. 11
0
def test_no_solutions1():
    equation = "6 * X^0 + 0 * X^2 = 1 * X^0"
    try:
        parser = Parser(equation)
        polynom = Polynom(parser)
    except:
        pass
Esempio n. 12
0
def test_no_solutions2():
    equation = "5 * X^0 = 8 * X^0"
    try:
        parser = Parser(equation)
        polynom = Polynom(parser)
    except:
        pass
Esempio n. 13
0
def test_big_degree3():
    equation = "1 * X^5 = 0 * X^0"
    try:
        parser = Parser(equation)
        Polynom(parser)
    except:
        pass
Esempio n. 14
0
def test_big_degree2():
    equation = "4 * X^0 + 4 * X^4 - 9.3 * X^2 = 0 * X^2"
    try:
        parser = Parser(equation)
        Polynom(parser)
    except:
        pass
Esempio n. 15
0
def test_big_degree4():
    equation = "6 * X^0 + 4 * X^18 - 9.3 * X^3 = 1 * X^0"
    try:
        parser = Parser(equation)
        polynom = Polynom(parser)
    except:
        pass
Esempio n. 16
0
def main(argv):
    file_name = argv[0]
    path = os.path.join(os.getcwd(), 'instances', file_name + '.col')
    graph = Parser().get_graph_from_file(path)
    start_time = datetime.now()
    if len(argv) >= 2:
        # choose algorithm from command line
        solution = globals()[argv[1]](graph)
    else:
        solution = ga1(graph)

    if solution:
        result_str = '\n\r'.join(['Coloring: %s' % solution.coloring,
                                  '# Bad edges: %s' % number_bad_edges(solution),
                                  '# Colors: %s' % number_colors(solution)])
    else:
        result_str = 'No solution found!'
    result_str += '\n\rSeconds: %s' % (datetime.now() - start_time).total_seconds()
    print(result_str)

    script_dir = os.path.dirname(__file__)
    directory = os.path.join(script_dir, 'results')
    if not os.path.exists(directory):
        os.makedirs(directory)
    with open(os.path.join(directory, '%s_%s.txt' % (file_name, datetime.now().strftime("%Y-%m-%d_%H-%M-%S"))), 'w') as f:
        f.write(result_str)
Esempio n. 17
0
def test_error_equal1():
    equation = "5 * X + 3 * X"
    try:
        parser = Parser(equation)
        polynom = Polynom(parser)
    except:
        pass
Esempio n. 18
0
def test_error_characters():
    equation = "5glezjjngv = 1 * X^0"
    try:
        parser = Parser(equation)
        polynom = Polynom(parser)
    except:
        pass
Esempio n. 19
0
def test_error_negative():
    equation = "6 * X^0 + -4 * X^2 = 1 * X^0"
    try:
        parser = Parser(equation)
        polynom = Polynom(parser)
    except:
        pass
 def makeInterpreter(self, text):
     from src.Lexer import Lexer
     from src.Parser import Parser
     from src.Interpreter import Interpreter
     lexer = Lexer(text)
     parser = Parser(lexer)
     interpreter = Interpreter(parser)
     return interpreter
 def load_file(self, file_name):
     with open(file_name) as file:
         self.data = file.readlines()
     self.data = [x.strip() for x in self.data]
     parser = Parser()
     self.data = parser.parse_iris_data(self.data)
     x = 0
     for i in range(len(self.data)):
         normalize_data = list(
             map(normalize, self.data[i][0:len(self.data[i]) - 1]))
         normalize_data.append(self.data[i][-1])
         self.data[i] = normalize_data
         if x % 2 == 0:
             self.test_data.append(self.data[i])
         else:
             self.train_data.append(self.data[i])
         x += 1
Esempio n. 22
0
def main(argv=sys.argv):
    parser = Parser()

    # Generate training data
    lexStr = parser.getLexFromXML("../docs/samePopularnonaukowe/uczace/")
    result = parser.parseLex(lexStr)
    parser.printToFile("../docs/samePopularnonaukowe/parsingOutput/train.data", result)

    #lexStr = parser.xxx("../docs/samePopularnonaukowe/uczace/")
    #parser.printToFile("../docs/samePopularnonaukowe/parsingOutput/train.data", lexStr)
    # Generate testing data
    lexStr = parser.getLexFromXML("../docs/samePopularnonaukowe/testowe/kap")
    result = parser.parseLex(lexStr)
    parser.printToFile("../docs/samePopularnonaukowe/parsingOutput/test.data", result)
Esempio n. 23
0
    def test_parsing_correct_configurations(self):

        subfolder = "correct_configs"

        # Test original example
        test_config_path = os.path.join(test_configs_folder, subfolder,
                                        "base_example")
        parser = Parser(test_config_path)

        lawn_size, mowers = parser.parse_config_file()
        assert lawn_size == (5, 5)
        assert mowers == [
            ((1, 2, "N"), ["L", "F", "L", "F", "L", "F", "L", "F", "F"]),
            ((3, 3, "E"), ["F", "F", "R", "F", "F", "R", "F", "R", "R", "F"])
        ]

        # Test with a big rectangle lawn
        test_config_path = os.path.join(test_configs_folder, subfolder,
                                        "with_big_rectangle_lawn")
        parser = Parser(test_config_path)

        lawn_size, mowers = parser.parse_config_file()
        assert lawn_size == (300, 500)
        assert mowers == [((80, 236, "W"), ["L", "F", "L", "F"]),
                          ((300, 378, "S"), ["F", "F", "R", "F"])]

        # Test with many mowers
        test_config_path = os.path.join(test_configs_folder, subfolder,
                                        "with_many_mowers")
        parser = Parser(test_config_path)

        lawn_size, mowers = parser.parse_config_file()
        assert lawn_size == (10, 10)
        assert mowers == [
            ((6, 4, "N"), ["L", "F"]), ((3, 3, "S"), ["R", "F", "F", "R"]),
            ((1, 2, "S"), ["L", "F", "L", "F", "L", "F", "L", "F", "F"]),
            ((2, 3, "E"), ["R", "F", "R", "L", "L", "R", "F"]),
            ((1, 8, "W"), ["L", "F", "L", "F"]),
            ((4, 3, "E"), ["F", "F", "R", "L"]),
            ((1, 4, "N"), ["L", "F", "L", "F", "L", "F", "L", "F", "F"]),
            ((4, 5, "N"), ["F", "F", "R", "F"]), ((1, 1, "N"), ["F", "F"]),
            ((3, 4, "E"), ["F", "R", "R", "F"]),
            ((8, 8, "W"), ["F", "L", "F", "F"]),
            ((3, 9, "E"), ["F", "F", "R", "F"]),
            ((10, 2, "S"), ["L", "F", "L", "F", "L", "F", "L", "F", "F"]),
            ((3, 5, "W"), ["L", "L", "L", "R", "R"]),
            ((6, 2, "N"), ["L", "F", "L", "F", "L", "F", "L", "F", "F"]),
            ((3, 7, "E"), ["F", "F", "L", "L", "R", "R", "L", "R", "R", "F"])
        ]
Esempio n. 24
0
    def find_solutions(self, query_text):

        query = Parser(query_text).parse_query()

        query_variable_map = {}
        variables_in_query = False

        # Find any variables within the query and return a map containing the variable name to actual
        # Prolog variable mapping we can later use to query our database.
        for argument in query.arguments:
            if isinstance(argument, Variable):
                variables_in_query = True
                query_variable_map[argument.name] = argument

        # Return a generator which iterates over the terms matching our query
        matching_query_terms = [item for item in self.database.query(query)]

        if matching_query_terms:
            if query_variable_map:

                # If our query has variables and we have matching query terms/items, we iterate over the query items
                # and our list of query variables and construct a map containing the matching variable names
                # and their values
                solutions_map = defaultdict(list)
                for matching_query_term in matching_query_terms:
                    matching_variable_bindings = query.match_variable_bindings(
                        matching_query_term)

                    # Itarate over the query variables and bind them to the matched database bindings
                    for variable_name, variable in query_variable_map.items():
                        solutions_map[variable_name].append(
                            matching_variable_bindings.get(variable))

                return solutions_map

            else:
                # If we have matching query items / terms but no variables in our query, we simply return true
                # to indicate that our query did match our goal. Otherwise, we return None
                return True if not variables_in_query else None
        else:
            # If we have no variables in our query, it means our goal had no matches, so we return False.
            # Otherwisewe simply return None to show no variable bindings were found.
            return False if not variables_in_query else None
Esempio n. 25
0
def main():
    parser = Parser()
    file_path = input("Insert file path: ")
    file_data = parser.read_input_file(file_path)

    delimiter_symbol = input("Insert delimiter symbol: ")
    delimiter_symbol = parser.delimiter_character(delimiter_symbol)
    directory = input("Type output directory to be outputted: ")
    outputted_file = parser.output_file(directory, basename(file_path))

    output_format = input("Type output file format(linhas[l] | colunas[c]): ")
    output_format = parser.file_format(output_format)

    parsed_data = parser.parse_file_data(file_data)
    parser.write_output_file(
        parsed_data, delimiter_symbol, outputted_file, output_format)
Esempio n. 26
0
def _test(n):
    input_path = pathlib.Path(current_dir / input_paths[n])
    expected_path = pathlib.Path(current_dir / expected_paths[n])

    solution = Solver(Parser(input_path)).solve()
    expected = Solver.to_string(
        [line for line in open(str(expected_path), 'r').read().splitlines()])

    assert solution == expected, 'Failed test_' + str(
        n) + ' -> ' + 'Expected:' + expected + ' != ' + 'Actual:' + solution
    print('Passed test_' + str(n) + ' -> ' + 'Expected:' + expected + ' == ' +
          'Actual:' + solution)
Esempio n. 27
0
def paintshop_ide():
    import pathlib

    input_paths = [
        'input_0.txt', 'input_1.txt', 'input_2.txt', 'input_3.txt',
        'input_messy_formatting.txt'
    ]

    for input_path in input_paths:
        path = pathlib.Path(
            pathlib.Path(__file__).parent / 'test' / input_path)
        solution = Solver(Parser(path)).solve()
        print(solution)
Esempio n. 28
0
def main():
    argparser = argparse.ArgumentParser(
        description='Generate an AST DOT file.')
    argparser.add_argument('fname', help='Pascal source file')
    args = argparser.parse_args()
    fname = args.fname
    text = open(fname, 'r').read()

    lexer = Lexer(text)
    parser = Parser(lexer)
    viz = ASTVisualizer(parser)
    content = viz.gendot()
    print(content)
class Preprocessor:
    def __init__(self, path, target):
        self.path = path
        self.target = target
        self.lexer = Lexer()
        self.parser = Parser()
        self.builder = Builder()

    def compile(self, minify):
        print(f'Compiling {self.path}')
        with open(self.path, 'r') as file:
            raw = file.read()
        self.lexer.tokenize(raw)
        self.parser.parse(self.lexer.tokens)
        html = self.builder.build(self.parser.dom)
        if minify: html = self.builder.minify(html)
        with open(self.target, 'w', newline='\n') as file:
            file.write(html)

    def watch(self, minify):
        print(f'Watching {self.path}')
        path = self.getSanitizedPath()
        eventHandler = EventHandler(path.fn, self.compile, [minify])
        observer = Observer()
        observer.schedule(eventHandler, path.dir, recursive=False)
        observer.start()
        try:
            while True:
                sleep(.1)
        except KeyboardInterrupt:
            observer.stop()
        observer.join()

    def getSanitizedPath(self):
        pathChunks = self.path.replace('\\', '/').split('/')
        return Namespace(dir='/'.join(pathChunks[:-1]), fn=pathChunks[-1])
Esempio n. 30
0
    def test_parsing_incorrect_syntax(self):

        subfolder = "incorrect_syntax"

        # Test with an empty config
        test_config_path = os.path.join(test_configs_folder, subfolder,
                                        "empty_config")
        parser = Parser(test_config_path)

        with pytest.raises(ValueError):
            parser.parse_config_file()

        # Test with incorrect number of lines in the file
        test_config_path = os.path.join(test_configs_folder, subfolder,
                                        "incorrect_number_of_lines")
        parser = Parser(test_config_path)

        with pytest.raises(ValueError):
            parser.parse_config_file()
Esempio n. 31
0
def main():
    commands_table = CommandsTable()
    code_writer = CodeWriter(commands_table)
    for argument in sys.argv[1:]:
        code_writer.set_file(argument)
        parser = Parser(argument, commands_table)
        while parser.has_more_commands():
            parser.advance()
            command_type = parser.command_type()
            argument1 = parser.arg1()
            argument2 = parser.arg2()
            if command_type == "C_ARITHMETIC":
                code_writer.write_arithmetic(argument1)
            if command_type == "C_PUSH":
                code_writer.write_push_pop("C_PUSH", argument1, argument2)
            if command_type == "C_POP":
                code_writer.write_push_pop("C_POP", argument1, argument2)

        code_writer.close()
Esempio n. 32
0
    def test_parsing_incorrect_mower_instructions(self):

        subfolder = "incorrect_mower_instructions"

        # Test with an incorrect direction
        test_config_path = os.path.join(test_configs_folder, subfolder,
                                        "incorrect_direction")
        parser = Parser(test_config_path)

        with pytest.raises(ValueError):
            parser.parse_config_file()

        # Test with a lower case direction
        test_config_path = os.path.join(test_configs_folder, subfolder,
                                        "lower_case_direction")
        parser = Parser(test_config_path)

        with pytest.raises(ValueError):
            parser.parse_config_file()
Esempio n. 33
0
def main(fname):
    # argparser = argparse.ArgumentParser(
    #     description='Generate an AST DOT file.'
    # )
    # argparser.add_argument(
    #     'fname',
    #     help='Pascal source file'
    # )
    # args = argparser.parse_args()
    # fname = args.fname
    text = open(fname, 'r').read()

    lexer = Lexer(text)
    parser = Parser(lexer)
    viz = ASTVisualizer(parser)
    content = viz.gendot()
    print(content)
    w = open('ast.dot', 'w')
    w.write(content)
Esempio n. 34
0
'''
@author: Jwang135
'''
from src.Parser import Parser
from flask import render_template
from flask import Flask
app = Flask(__name__)

projects = Parser.svn_list_parser('Data/svn_list.xml')
Parser.svn_log_parse('Data/svn_log.xml',projects)

# Learn from https://github.com/mukichou/cs242-1
@app.route('/')
def home_page():
    return render_template('index.html',projects=projects)


@app.route('/mp1')
def assignment_page(name=None):
    return render_template('projects.html',
                           projects=projects,
                           name=name)

@app.route('/mp2')
def assignment_page2(name=None):
    return render_template('projects_2.html',
                           projects=projects,
                           name=name)
    
@app.route('/<name>/files')
from src.LexicalException import LexicalException
from src.Memory import Memory
from src.Parser import Parser
from src.ParserException import ParserException

__author__ = 'thamilton'

if __name__ == "__main__":
    try:
        parser = Parser("/Users/thamilton/PycharmProjects/Project_2/test_data/test3.e")
        parser.feature().execute()
        memory = Memory()
        memory.display_memory()
    except (OSError, IOError, ValueError, Exception, LexicalException, ParserException) as e:
        print(e)