def test_check_required_files():
    path = '../circuitfiles/amp/'
    file_hand = FileHandler(path)
    file_hand.form_simulation_environment(4)
    assert os.path.isdir('../circuitfiles/amp_temp/0')
    assert os.path.isdir('../circuitfiles/amp_temp/1')
    assert os.path.isdir('../circuitfiles/amp_temp/2')
    assert os.path.isdir('../circuitfiles/amp_temp/3')
Beispiel #2
0
 def build_abstract_syntax_tree_dir(self, main_dir):
     for dirName, subdirList, file_list in FileHandler.walklevel(main_dir.description, level=0):
         for file_name in file_list:
             # add extension logic here
             if self.base_node.code is None or file_name.lower().endswith("."+self.base_node.code):
                 child = main_dir.open_new_context(self.next_node_id(), "file", description=os.path.join(dirName, file_name))
                 self.build_abstract_syntax_tree(child)
         for subdir in subdirList:
             next_dir = main_dir.open_new_context(self.next_node_id(), "dir", description=os.path.join(dirName, subdir))
             self.build_abstract_syntax_tree_dir(next_dir)
Beispiel #3
0
    def build_abstract_syntax_tree(self, main_node):
        if main_node.code is None and main_node.context_type == "file" and main_node.description is not None:
            main_node.code = FileHandler.file_to_string(main_node.description)

        if main_node.context_type == "dir":
            self.build_abstract_syntax_tree_dir(main_node)
            return

        main_node.start = 0
        main_node.end = len(main_node.code)
        main_node.line_start = 1
        main_node.line_end = StringTools.count_lines(main_node.code)

        current_context = main_node
        line = 1
        last_n = None
        offset = main_node.start

        while offset < main_node.end:
            previous_context = current_context
            # increase line counter at end of loop whenever you find '\n'
            line_flag = False
            if offset != last_n and main_node.code[offset] == '\n':
                last_n = offset  # if \n is not eaten, we must be sure we do not compute the line skip more than once
                line_flag = True

            # close priority contexts: ignore all but the closure, used for strings and comments
            [current_context, offset, stop_flag] = \
                self.priority_rule_check_close(main_node=main_node, rules=self.priority_context_rules,
                                               current_context=current_context, offset=offset, line=line)

            # here, we are sure we are not in a priority rule
            if not stop_flag:
                [current_context, offset, stop_flag] = \
                    self.priority_rule_check_open(main_node=main_node, rules=self.priority_context_rules,
                                                  current_context=current_context, offset = offset, line=line)

            # Non priority contexts:
            if not stop_flag:
                [current_context, offset, stop_flag] = \
                    self.non_priority_rule_check(main_node=main_node, rules=self.context_rules,
                                                 current_context=current_context, offset=offset, line=line)

            # if we did not find anything, remember to skip to next character
            if not stop_flag:
                offset = offset + 1

            # increase line counter at end of loop whenever you find '\n'
            if line_flag:
                line = line + 1
Beispiel #4
0
def generate_file_doc(base_node, out, prepend=""):
    filename = base_node.context_type
    destination = out + '/index.html'

    if base_node.description:
        filename = REGEX_PATH_SPLIT.split(base_node.description)
        filename = filename[len(filename) - 1]
        destination = out + '/' + filename[:len(filename) - 3] + '.html'

    destination = Path(destination)
    template_location = Path(gen_directory + '/index.html')
    if template_location != destination:
        fh.copy_file(template_location, destination)

    fh.replace_in_file("assets/",
                       prepend + "assets/",
                       destination,
                       replace_all=True)
    fh.replace_in_file('@filename', filename, destination, replace_all=True)

    generate_code_doc(base_node, destination)
Beispiel #5
0
from src.OzDocParser import OzDocParser
from src.ArgumentsHandler import parse_args
from src import FileHandler

if __name__ == '__main__':

    # Recover program arguments (file, dir, text, out, settings, template, docgen)
    args = parse_args()
    try:
        os.makedirs(args.out)
    except FileExistsError:
        if not os.access(args.out, os.W_OK):
            raise IOError(errno.EIO, "Error writing out folder", args.out)

    # Check program mode
    settings = FileHandler.import_module("settings", args.settings)
    if args.file[0] is not None:  # file mode
        parser = OzDocParser(
            context_type="file",
            description=args.file[0],
            priority_context_rules=settings.priority_context_rules,
            context_rules=settings.context_rules)

    elif args.dir is not None:  # directory mode
        if args.extension is None:
            parser = OzDocParser(
                context_type="dir",
                description=args.dir,
                priority_context_rules=settings.priority_context_rules,
                context_rules=settings.context_rules)
        else:
Beispiel #6
0
def run(parser, settings, out):
    destination = out + '/index.html'
    code = parser.base_node.code
    # Creation of the repository of all functions
    fun_repo = OzDocParser.build_link_context_with_repo(
        parser.base_node, settings.fun_keyword, settings.def_keyword)
    OzDocParser.link_following_regex_to_repo(
        parser.base_node,
        fun_repo,
        settings.fun_regex,
        exception=settings.comment_keyword)

    # Creation of the repository of all function calls
    call_repo = OzDocParser.build_context_repo_not_in(
        parser.base_node, settings.def_keyword,
        ListTools.get_list_column(fun_repo, 1))
    # Creation of the repository of all comments
    comment_repo = OzDocParser.build_context_repo(parser.base_node,
                                                  settings.comment_keyword)
    OzDocParser.link_all_regex_to_repo(parser.base_node, comment_repo,
                                       settings.ozdoc_tag_regex)

    # Generating the body of the table containing all of the functions.
    doc, tag, text = Doc().tagtext()
    with tag('tbody'):
        for function in fun_repo:
            funcname = function[2]
            if funcname != '$':
                with tag('tr'):
                    with tag('td'):
                        text(funcname)
                    with tag('td'):
                        description = ""
                        prev_sister = function[0].find_previous_sister()
                        if prev_sister:
                            if prev_sister.context_type in settings.comment_keyword:  # if previous sister is a comment
                                description = code[prev_sister.
                                                   start:prev_sister.
                                                   end].split('\n')[0][:80]
                                description = description.lstrip(
                                    '/*% ').rstrip('/*% ')
                        text(description)
    new_tablebody = doc.getvalue()
    fh.replace_in_file('@tablebody', new_tablebody, destination)

    # Generating the head of the table containing all of the functions.
    doc, tag, text = Doc().tagtext()
    with tag('thead'):
        with tag('tr'):
            with tag('th'):
                text('Function')
            with tag('th'):
                text('Description')
    new_tablehead = indent(doc.getvalue())
    fh.replace_in_file('@tablehead', new_tablehead, destination)

    # Generating the section containing the details of all of the functions.
    doc, tag, text, line = Doc().ttl()
    with tag('ul', klass='blockList'):
        with tag('li', klass='blockList'):
            with tag('ul', klass='blockList'):
                with tag('li', klass='blockList'):
                    for function in fun_repo:
                        funcname = function[2]
                        if funcname != '$':
                            line('h4', funcname)
                            with tag('pre', style='font-style: italic;'):
                                text(code[function[1].start:function[1].end])

                                # @TODO
                                # Check if the @throws tag is used.
                                # (get sister, make taglist)
                                # throws_found = tag_found_in_comment('@throws', taglist)
                                # # If exception thrown, add :
                                # text('\n\t\t\tthrows ')
                                # line('a', 'Insert Exception Name', href='')

                            description = ""
                            prev_sister = function[0].find_previous_sister()
                            k = -1  # index of previous sister (if it is a comment) in comment_repo

                            if prev_sister:
                                if prev_sister.context_type in settings.comment_keyword:
                                    # Entered if previous sister is a comment
                                    start = prev_sister.start
                                    end = prev_sister.end

                                    # Find it in comment_repo as well.
                                    for i, x in enumerate(comment_repo):
                                        if x[0].start == prev_sister.start:
                                            k = i
                                            for tag_found in comment_repo[k][
                                                    1]:
                                                if tag_found[
                                                        0] in supported_tags:
                                                    end = tag_found[1]
                                                    break
                                            break
                                    description = code[start:end]

                            with tag('pre'):
                                description = description.split('\n')
                                for d in description:
                                    line('code',
                                         d.lstrip('/*% '),
                                         klass='block')

                            if k != -1:
                                if comment_repo[k][1]:
                                    with tag('dl'):
                                        taglist = comment_repo[k][1]
                                        end_of_comment = comment_repo[k][0].end

                                        for i in range(len(supported_tags)):
                                            found = tag_found_in_comment(
                                                supported_tags[i], taglist)
                                            if found:
                                                make_tagged_section(
                                                    supported_tags[i],
                                                    supported_names[i],
                                                    supported_labels[i],
                                                    taglist, end_of_comment,
                                                    tag, text, line, code)

                            # Making the button to show the Source Code.
                            with tag('dt'):
                                line('span', 'Source Code:', klass='codeLabel')
                            with tag('dd'):
                                id = str(function[0].node_id)
                                line('button',
                                     'Show',
                                     onclick='show' + id + '()')
                                with tag('pre', id=id, style='display: none;'):
                                    line('code', (code[function[0].
                                                       start:function[0].end]))
                                show_fun_def = 'function %s() {' \
                                               '  var x = document.getElementById("%s");' \
                                               '  if (x.style.display === "none") {' \
                                               '    x.style.display = "block";' \
                                               '  } else {' \
                                               '    x.style.display = "none";' \
                                               '   }' \
                                               '}' % ('show' + id, id)
                                line('script', show_fun_def)

    new_functiondetails = indent(doc.getvalue())
    fh.replace_in_file('@functiondetails', new_functiondetails, destination)
Beispiel #7
0
                       f"but given {multi_thread}.")

with open(cfg_path) as file:
    yaml_file = yaml.load(file, Loader=yaml.FullLoader)
    CIRCUIT_PROPERTIES = yaml_file["Circuit"]
    SPEA2_PROPERTIES = yaml_file["SPEA2"]

if not os.path.isdir(CIRCUIT_PROPERTIES["path_to_output"]):
    raise SystemExit(f"There is no such direction "
                     f"{CIRCUIT_PROPERTIES['path_to_output']}")

if __name__ == "__main__":
    from src import FileHandler, process

    # Create temp folder to perform simulations
    file_handler = FileHandler(CIRCUIT_PROPERTIES['path_to_circuit'])
    file_handler.form_simulation_environment(multi_thread)
    path = file_handler.get_folder_path()

    # start time_perf counter.
    start = time.perf_counter()

    # start the process
    saved_file_path = process(CIRCUIT_PROPERTIES, SPEA2_PROPERTIES, path,
                              multi_thread, saving_mode, only_cct)

    # stop time_perf counter
    stop = time.perf_counter()

    constraints_as_str = [
        k + '->' + i + ':' + str(j)
Beispiel #8
0
from src import FileHandler
from src.Iterator import Iterator
from src.PerfNum import isPerfect
import time
import sys

path = sys.argv[1]
n = int(sys.argv[2])
start_time = time.time()
data = FileHandler.fileToArray(path)

if n <= len(data):
    myiterator = iter(data)
    generator = Iterator(len(data), n)
    for index in generator:
        sum = 0
        for i in index:
            sum = sum + data[i]
        if isPerfect(sum):
            print("La combinacion de las posiciones: " + str(index) +
                  " genera el numero perfecto: " + str(sum))
        else:
            pass
else:
    print("No puede haber más valores a permutar que valores en la lista")
print("Ejecución terminada")
Beispiel #9
0
def make_table_section(type, main_repo, sub_repo, code, destination, fun_repo,
                       class_repo, meth_repo, comment_repo):
    if type != 'function' and type != 'class':
        return
    iname = 1 if type == 'class' else 2  # Index of the repository column containing the name of the class/function

    repo_is_useful = bool(main_repo)
    if type == 'function':
        repo_is_useful = bool(main_repo) and any(
            map(lambda e: e[iname] != '$', main_repo))

    if repo_is_useful:

        ################################################################################################################
        #                                       Generating the head of the table                                       #
        ################################################################################################################
        doc, tag, text = Doc().tagtext()
        with tag('thead'):
            with tag('tr'):
                with tag('th'):
                    text(type.capitalize())
                if type == 'function':
                    with tag('th'):
                        text('Type')
                with tag('th'):
                    text('Description')
        fh.replace_in_file('@' + type + 'tablehead', indent(doc.getvalue()),
                           destination)

        ################################################################################################################
        #                                       Generating the body of the table                                       #
        ################################################################################################################
        doc, tag, text, line = Doc().ttl()
        with tag('tbody'):
            for elem in main_repo:
                elemname = elem[iname]
                if type == 'function' and elemname == '$':
                    continue
                with tag('tr'):
                    with tag('td'):
                        with tag('a',
                                 href="#" + elemname + str(elem[0].node_id)):
                            text(elemname)
                    if type == 'function':
                        with tag('td'):
                            text(elem[0].context_type)
                    with tag('td'):
                        description = ""
                        prev_sister = elem[0].find_previous_sister()
                        if prev_sister:
                            if prev_sister.context_type in settings.comment_keyword:  # if previous sister is a comment
                                # Default value for the description
                                description = code[prev_sister.
                                                   start:prev_sister.
                                                   end].split('\n')[0][:200]
                                description = description.lstrip(
                                    '/*% ').rstrip('/*% ')

                                # If a summary tag is in use
                                # @TODO : transform this next bit into a function
                                # Find it in comment_repo as well.
                                for i, x in enumerate(comment_repo):
                                    if x[0].start == prev_sister.start:
                                        k = i
                                        taglist = comment_repo[k][1]
                                        if tag_found_in_comment(
                                                SUMMARY_TAG, taglist):
                                            for j, tag_found in enumerate(
                                                    taglist):
                                                if tag_found[0] == SUMMARY_TAG:
                                                    start = tag_found[1]
                                                    end = taglist[j + 1][1] - 1 if j < (len(taglist) - 1) else \
                                                    comment_repo[k][0].end
                                                    description = code[
                                                        start:end][(
                                                            len(SUMMARY_TAG)
                                                        ):].rstrip(' ').rstrip(
                                                            '/*%')
                                                    break
                                            break
                        text(description)

                        if type == 'class':
                            # Getting methods of the class
                            methlist = []
                            for meth in sub_repo:
                                if meth[0].start > elem[0].start and meth[
                                        0].end < elem[0].end:
                                    methlist.append(meth)
                            if methlist:
                                doc.stag('br')
                                line('u', 'Contains methods')
                                text(' : ')
                                for i, meth in enumerate(methlist):
                                    if i > 0:
                                        doc.asis('&nbsp;')
                                        text(',')
                                        doc.asis('&nbsp;')
                                    with tag('a',
                                             href="#" + meth[1] +
                                             str(meth[0].node_id)):
                                        text(meth[1])
                                text('.')

                        # Making context hierarchy
                        context_hierarchy = make_context_hierarchy(
                            elem[0].parent if elem[0].parent else elem[0],
                            fun_repo, class_repo, meth_repo)
                        if context_hierarchy:
                            doc.stag('br')
                            with tag('i'):
                                text('(from: ' + context_hierarchy + ')')
        fh.replace_in_file('@' + type + 'tablebody', indent(doc.getvalue()),
                           destination)

        ################################################################################################################
        #                 Generating the section containing details about the functions or methods                    #
        ################################################################################################################
        if type == 'class' and not bool(sub_repo):
            empty = ""
            fh.replace_in_file('@' + type + 'details', empty, destination)
        else:
            doc, tag, text, line = Doc().ttl()
            with tag('ul', klass='blockList'):
                with tag('li', klass='blockList'):
                    if type == 'function':
                        line('h2', 'Function details')
                        make_details_section(type, main_repo, code,
                                             destination, fun_repo, class_repo,
                                             meth_repo, comment_repo, doc, tag,
                                             text, line)
                    else:  # meaning type == 'class'
                        for klass in main_repo:
                            line('h2',
                                 klass[1],
                                 id=klass[1] + str(klass[0].node_id))
                            make_details_section(type,
                                                 sub_repo,
                                                 code,
                                                 destination,
                                                 fun_repo,
                                                 class_repo,
                                                 meth_repo,
                                                 comment_repo,
                                                 doc,
                                                 tag,
                                                 text,
                                                 line,
                                                 klass=klass)
            fh.replace_in_file('@' + type + 'details', indent(doc.getvalue()),
                               destination)

    else:
        empty = ""
        fh.replace_in_file('@' + type + 'tablehead', empty, destination)
        fh.replace_in_file('@' + type + 'tablebody', empty, destination)
        fh.replace_in_file('@' + type + 'details', empty, destination)
Beispiel #10
0
def generate_code_doc(base_node, destination):
    code = base_node.code
    OzDocParser.fuse_similar_successive_contexts(
        base_node, settings.inline_comment_keyword)

    ###################################################################################################################
    #                                     Generating abstract syntax tree                                             #
    ###################################################################################################################
    doc, tag, text = Doc().tagtext()
    with tag('pre', klass='oz-code'):
        doc.asis(
            gen_html_ast(base_node, ROOT_CONTEXTS + settings.oz_block_keywords,
                         ["\'", "\"", "`"]))
    ast = doc.getvalue()
    fh.replace_in_file('@abstract_syntax_tree', ast, destination)

    ###################################################################################################################
    #                                          Generating source code                                                 #
    ###################################################################################################################
    doc, tag, text = Doc().tagtext()
    with tag('pre', klass='line-numbers'):
        with tag('code', klass='language-oz'):
            text(code)
    source_code = doc.getvalue()
    fh.replace_in_file('@source_code', source_code, destination)

    ###################################################################################################################
    #                 Creation of repositories containing functions, classes, comments, etc.                          #
    ###################################################################################################################
    try:
        fun_repo = OzDocParser.build_link_context_with_repo(
            base_node, settings.fun_keyword, settings.def_keyword)
        OzDocParser.link_following_regex_to_repo(
            base_node,
            fun_repo,
            settings.declarations_name_regex,
            exception=settings.comment_keyword)
        # Example of how to print a repository:
        # PrintTools.print_repo(fun_repo)

        fun_call_repo = OzDocParser.build_context_repo_not_in(
            base_node, settings.def_keyword,
            ListTools.get_list_column(fun_repo, 1))

        class_repo = OzDocParser.build_context_repo(base_node,
                                                    settings.class_keyword)
        OzDocParser.link_following_regex_to_repo(
            base_node,
            class_repo,
            settings.declarations_name_regex,
            exception=settings.comment_keyword)

        meth_repo = OzDocParser.build_context_repo(base_node,
                                                   settings.meth_keyword)
        OzDocParser.link_following_regex_to_repo(
            base_node,
            meth_repo,
            settings.meth_regex,
            exception=settings.comment_keyword)

        comment_repo = OzDocParser.build_context_repo(base_node,
                                                      settings.comment_keyword)
        OzDocParser.link_all_regex_to_repo(base_node, comment_repo,
                                           settings.ozdoc_tag_regex)
    except Exception as exception:
        doc, tag, text, line = Doc().ttl()
        with tag('h2', style='color: #FF0000; font-weight: bold;'):
            text("You did not input a vaild, errorless Oz file.")
            doc.stag('br')
            text("This file could thus not be parsed correctly.")
            doc.stag('br')
            text("(Hint: look for unclosed parentheses and curly brackets)")
            doc.stag('br')
            doc.stag('br')
            text(
                "The following exception happened during creation of repositories:"
            )
            doc.stag('br')
            line('i', exception.__class__.__name__)
        fh.replace_in_file('@general_info', doc.getvalue(), destination)

        for type in ['function', 'class']:
            fh.replace_in_file('@' + type + 'tablehead', "", destination)
            fh.replace_in_file('@' + type + 'tablebody', "", destination)
            fh.replace_in_file('@' + type + 'details', "", destination)
        return

    ###################################################################################################################
    #                                     Generating general information                                              #
    ###################################################################################################################
    doc, tag, text, line = Doc().ttl()
    with tag('div', klass='general-info'):
        title = base_node.context_type
        if base_node.description:
            title = REGEX_PATH_SPLIT.split(base_node.description)
            title = title[len(title) - 1]
        line('h2', title, style='font-weight: bold;')
        doc.stag('br')

        nothing = True

        # Section for file summary
        if base_node.children:
            if base_node.children[0].context_type in settings.comment_keyword:
                taglist = comment_repo[0][1]
                if tag_found_in_comment(SUMMARY_TAG, taglist):
                    nothing = False
                    for i, tag_found in enumerate(taglist):
                        if tag_found[0] == SUMMARY_TAG:
                            # Content
                            start = tag_found[1]
                            end = taglist[i + 1][1] - 1 if i < (
                                len(taglist) - 1) else comment_repo[0][0].end
                            content = code[start:end][(
                                len(SUMMARY_TAG)):].rstrip(' ').rstrip('/*%')
                            line('font', content, size='+1')
                            doc.stag('br')
                            doc.stag('br')
                            break

        # Section for context hierarchy, if not root node
        if base_node.parent:
            nothing = False
            line('h3', 'From:')
            with tag('ul'):
                with tag('li'):
                    text(
                        make_context_hierarchy(base_node.parent,
                                               fun_repo,
                                               class_repo,
                                               meth_repo,
                                               go_all_the_way=True))
            doc.stag('br')

        # Section for unusual keywords found
        unusual_kw = []
        USUAL_CONTEXT = USUAL_KEYWORDS + settings.fun_keyword + settings.class_keyword + settings.meth_keyword \
                        + settings.comment_keyword + settings.def_keyword + settings.string_keyword\
                        + ROOT_CONTEXTS + ["[]", "var", "atom"]
        for node in base_node.iter_children():
            if node.context_type not in USUAL_CONTEXT:
                unusual_kw.append(node)
        if unusual_kw:
            nothing = False
            line('h3', 'Non-frequent keywords found:')
            with tag('ul'):
                for kw in unusual_kw:
                    with tag('li', klass='oz-code'):
                        line('span',
                             kw.context_type,
                             klass=OZ_KEYWORD_SIMPLE_CLASS)
                        text(", at line " + str(kw.line_start))
                        hierarchy = make_context_hierarchy(
                            kw.parent if kw.parent else kw,
                            fun_repo,
                            class_repo,
                            meth_repo,
                            get_root=False)
                        if hierarchy:
                            text(" (in ")
                            line('i', hierarchy)
                            text(")")
            doc.stag('br')

        # Section for TODO tags
        todotags = []
        for comment in comment_repo:
            taglist = comment[1]
            for i, tag_found in enumerate(taglist):
                if tag_found[0] == TODO_TAG:
                    # Origin (for context hierarchy)
                    origin = comment[0]
                    next_sister = origin.find_next_sister()
                    if next_sister:
                        if next_sister.context_type in settings.fun_keyword \
                                or next_sister.context_type in settings.meth_keyword \
                                or next_sister.context_type in settings.class_keyword:
                            origin = next_sister

                    if origin.context_type in settings.comment_keyword:
                        if origin.parent:
                            origin = origin.parent

                    # Content
                    start = tag_found[1]
                    end = taglist[i + 1][1] - 1 if i < (len(taglist) -
                                                        1) else comment[0].end
                    content = code[start:end][(
                        len(TODO_TAG)):].rstrip(' ').rstrip('/*%')

                    if todotags:
                        if origin.start == todotags[len(todotags) -
                                                    1][0].start:
                            todotags[len(todotags) - 1][1].append(content)
                        else:
                            todotags.append([origin, [content]])
                    else:
                        todotags.append([origin, [content]])
        if todotags:
            nothing = False
            with tag('div', klass='TODO'):
                line('h3', 'TODO', style='font-weight: bold;')
                for t in todotags:
                    with tag('ul'):
                        with tag('li'):
                            text(
                                make_context_hierarchy(t[0], fun_repo,
                                                       class_repo, meth_repo) +
                                ', at line ' + str(t[0].line_start) + ':')
                            for content in t[1]:
                                with tag('ul'):
                                    line('li', content)
            doc.stag('br')

        if nothing:
            text('No unusual information concerning ' + title + '.')
    fh.replace_in_file('@general_info', doc.getvalue(), destination)

    ###################################################################################################################
    #                                  Generating class and function tables                                           #
    ###################################################################################################################
    make_table_section('class', class_repo, meth_repo, code, destination,
                       fun_repo, class_repo, meth_repo, comment_repo)
    make_table_section('function', fun_repo, None, code, destination, fun_repo,
                       class_repo, meth_repo, comment_repo)