Esempio n. 1
0
def gen_html(estimate):
    print("Rendering HTML")
    loader = FileLoader('.')
    template = loader.load_template('template.html')
    estimate_txt = estimate.strftime("%d %B")
    res = template.render(
        {
            'estimate':
            estimate_txt,
            'goalMs':
            round(estimate.timestamp()),
            'today':
            date.today().strftime("%d %B"),
            'ver':
            round(datetime.now().timestamp()),
            'goal':
            int(GOAL),
            'lastEntry':
            datetime.strptime(last_entry, "%Y-%m-%d").strftime("%d %B"),
            'vaccinated':
            first_dose
        },
        loader=loader).encode('utf-8')
    f = open("index.html", "w")
    f.write(res.decode("utf-8"))
    f.close()
Esempio n. 2
0
def gen():
    xmlTree = ET.parse('../../UserFiles/hw_conf.xml')
    root = xmlTree.getroot()

    number_of_node = int(root[1][0].text) * int(root[1][1].text)

    xmlTree = ET.parse('../../UserFiles/mapping.xml')
    root = xmlTree.getroot()

    # create a dictionary of list from mapping xml file
    mapping_dict = {}
    for element in root:
        if element.tag == 'process_mapping':
            mapping_dict[element.get('target')] = [
                element.get('target'),
                element.get('target').split('_')[1]
            ]

    list_map = list(mapping_dict)
    i = 0
    sw_scripts = []
    for i in range(len(list_map)):
        sw_scripts.clear()
        sw_scripts.append({
            'nodeName': list_map[i],
            'cpuName': 'nios2_' + list_map[i].split('_')[1],
            'index': list_map[i].split('_')[1]
        })
        loader = FileLoader('')
        template = loader.load_template('Templates/sw_script_template.sh')
        with open('../../sw_scripts/create_' + list_map[i] + '.sh',
                  'w',
                  encoding='utf-8') as f:
            f.write(template.render(locals()))
Esempio n. 3
0
    def build_html(self):
        loader = FileLoader('html')
        template = loader.load_template('ladder_template.html')
        players = []

        for name in self.table:
            players.append({'name': name,
                            'rank': self.table.index(name) + 1})

        return template.render(locals(), loader=loader).encode('utf-8')
Esempio n. 4
0
    def __init__(self, group, ladder):
        self.group = group
        self.loader = FileLoader('html')
        self.template = self.loader.load_template('ladder_template.html')

        # put data in format ready for html templating
        self.html_players = []
        i = 0
        for player in ladder:
            i += 1
            self.html_players.append({'name': player.name, 'rank': i})
Esempio n. 5
0
def create_video_page(post):

    try:
        loader = FileLoader('html')
        template = loader.load_template('video.html')
        date = parser.parse(post["created_time"])
        video_id = post["id"]
        # TODO actually use the template to generate a page...

        src = ""
        if (post.has_key("object_id")):
            if not (download_other_groups_videos or download_group_videos):
                return
            src = "https://www.facebook.com/photo.php?v=" + post["object_id"]
        elif (post.has_key("source")):
            if not download_other_sites_videos: return
            src = post["source"]
        elif (post.has_key("link")):
            if not download_other_sites_videos: return
            src = post["link"]
        else:
            return

        # Download the video
        result = ydl.extract_info(src, download=False)
        if 'entries' in result:
            # Can be a playlist or a list of videos
            video = result['entries'][0]
        else:
            # Just a video
            video = result

        #print("Downloading Thumbnail: " + video["thumbnail"])
        download_picture(video["thumbnail"], video_id, True)

        video_name = video_id + "." + video["ext"]

        video_url = os.path.join("content", "videos", video_name)
        if not os.path.exists(video_url):
            tempfile = video["id"] + video["ext"]
            print "downloading " + video_name
            result = ydl.extract_info(src, download=True)
            os.rename(tempfile, video_url)

        post["video"] = video_name

    except facebook.GraphAPIError as e:
        print "Download failed for :" + str(video_id) + "\nError: " + e.message
    except youtube_dl.utils.DownloadError as e:
        print "Download failed for :" + str(video_id) + "\nError: " + e.message
    except KeyError as e:
        print "Complex output for data on this video :" + str(
            video_id) + "\nError: " + e.message
def main(argv):
    baseFolder = '/etc/nginxTemplates'
    outputFilePath = "/etc/nginx/nginx.conf"

    # Format template with values from environment
    loader = FileLoader(baseFolder)
    template = loader.load_template('nginx.conf.tmpl')
    renderedTemplate = template.render(templateValues,
                                       loader=loader).encode('utf-8')

    # Save into logstash folder
    with open(outputFilePath, "w") as text_file:
        text_file.write("{0}".format(renderedTemplate))
def create_html_summary():
    loader = FileLoader(".")
    template = loader.load_template('index.html')
    repos = requests.get(
        "https://api.github.com/orgs/nationalarchives/teams/transfer-digital-records/repos?per_page=100",
        headers=headers).json()
    filtered_repos = sorted([repo["name"] for repo in repos if not repo["archived"] and not repo["disabled"]])

    for repo in filtered_repos:
        versions = get_versions(repo)
        if versions is not None:
            releases.append(versions)
    with open("output.html", "w") as output:
        output.write(template.render({'releases': releases}, loader=loader))
Esempio n. 8
0
def index_page(posts, pg_count, more_pages):
    index_name = os.path.join("content", "posts", str(pg_count) + ".html")

    with open(index_name, 'wb') as f:
        loader = FileLoader('html')
        template = loader.load_template('post.html')
        f.write(
            template.render(
                {
                    'posts': posts,
                    'pg_count': pg_count + 1,
                    'more_pages': more_pages
                },
                loader=loader).encode('utf-8'))
Esempio n. 9
0
def gen():
    xmlTree = ET.parse('../UserFiles/hw_conf.xml')
    root = xmlTree.getroot()
    number_of_node = int(root[1][0].text) * int(root[1][1].text)

    i = 0
    for i in range(number_of_node):
        loader = FileLoader('')
        template = loader.load_template('Templates/makefile')
        with open('../packet_transaction_lib/inc/header_' + str(i) +
                  '/makefile',
                  'w',
                  encoding='utf-8') as f:
            f.write(template.render(locals()))
Esempio n. 10
0
def create_photo_page(picture_id):

    try:
        post = graph.get_object(picture_id)

        # for a reason I ignore the message from the post of this image
        # is in the name...
        if ("name" in post):
            post["name"] = cgi.escape(post["name"]).replace('\n', '<br />')
        if ("message" in post):
            post["message"] = cgi.escape(post["message"]).replace(
                '\n', '<br />')

        loader = FileLoader('html')
        template = loader.load_template('photo.html')
        date = parser.parse(post["created_time"])

        # TODO verify that the extension is correct...
        download_picture(post["source"] + "?type=large", picture_id)
        photo_url = os.path.join("..", "pictures", picture_id + ".jpg")

        file_name = os.path.join("content", "photos", post["id"] + ".html")

        # Download all the images for the comments.
        if post.has_key("comments"):
            post["all_comments"] = process_comments(post)

        with open(file_name, 'wb') as f:
            f.write(
                template.render(
                    {
                        'post': post,
                        'date': date,
                        'photo': photo_url
                    },
                    loader=loader).encode('utf-8'))
        return True
    except facebook.GraphAPIError as e:
        print "Oops!  failed to get this object:" + str(
            picture_id) + "\nError: " + e.message
        return False
    except KeyError as e:
        print "Oops! Failed to find information for this image:" + str(
            picture_id) + "\nError: " + e.message
        return False
Esempio n. 11
0
def ProcessSlpTmpl(tmplfile):
    service_filter = 'http.rdf'
    services_list = GetSlpServices(service_filter)

    # loader = FileLoader('html')
    loader = FileLoader('.')
    template = loader.load_template(tmplfile)
    generated_html = template.render(
        {
            'filter': service_filter,
            'services': services_list
        }, loader=loader).encode('utf-8')

    outfile = tmplfile + ".htm"
    fil = open(outfile, 'w')
    fil.write(generated_html)
    fil.close()
    return outfile
Esempio n. 12
0
def gen():
    xmlTree = ET.parse('../UserFiles/mapping.xml')
    root = xmlTree.getroot()

    # create a dictionary of list from mapping xml file
    mapping_dict = {}
    i = 0
    for element in root:
        if element.tag == 'process_mapping':
            mapping_dict[element.get('target')] = [element.get('target'), element.get('target').split('_')[1]]

    list_map = list(mapping_dict)
    downloadShell_prjs = []
    for i in range(len(list_map)):
            downloadShell_prjs.append({'nodeName': list_map[i],
                                       'elfName': list_map[i] + '.elf',
                                       'instanceID': list_map[i].split('_')[1]})
    loader = FileLoader('')
    template = loader.load_template('Templates/download_template.sh')

    with open('../download.sh', 'w', encoding='utf-8') as f:
        f.write(template.render(locals()))
Esempio n. 13
0
def _get_service_file(squadron_dir,
                      service_name,
                      service_ver,
                      filename,
                      on_error=None,
                      config=None):
    """
    Grabs the named service file in a service directory

    Keyword arguments:
        squadron_dir -- base directory
        service_name -- the name of the service
        service_ver -- the version of the service
        filename -- the name of the service file without the extension
        empty_on_error -- if true, returns an empty dict instead of raising error
        config -- if a dict, uses it to template the file before loading it
    """
    ex = None
    for ext in extensions:
        try:
            serv_dir = os.path.join(squadron_dir, 'services', service_name,
                                    service_ver)
            service_file = os.path.join(serv_dir, filename + ext)
            if config:
                loader = FileLoader(squadron_dir)
                template = loader.load_template(service_file)
                return yaml.load(template.render(config, loader=loader))
            else:
                with open(service_file, 'r') as sfile:
                    return yaml.load(sfile.read())
        except (OSError, IOError) as e:
            if e.errno == errno.ENOENT:
                ex = e
            else:
                raise e

    if on_error is not None:
        return on_error
    raise ex
Esempio n. 14
0
def gen():
    xmlTree = ET.parse('../../UserFiles/hw_conf.xml')
    root = xmlTree.getroot()

    number_of_node = int(root[1][0].text) * int(root[1][1].text)

    xmlTree = ET.parse('../../UserFiles/application.xml')
    root = xmlTree.getroot()

    processes = []

    for element in root:
        if element.tag == 'process':
            temp = {}
            temp['process_name'] = element.get('name')
            temp['numOfInp'] = element.get('numOfInp')
            temp['numOfOut'] = element.get('numOfOut')
            for subElement in element:
                temp2 = {}
                if subElement.tag == 'port':
                    temp2['ID'] = subElement.get('ID')
                    temp2['name'] = subElement.get('name')
                    temp2['type'] = subElement.get('type')
                    temp2['direction'] = subElement.get('direction')
                    temp2['numOfToken'] = subElement.get('numOfToken')
                    temp.update({subElement.get('name'): temp2})
                elif subElement.tag == 'source_file':
                    temp.update(
                        {'source_file': subElement.get('name').split('_')[1]})
            processes.append(temp)

    i = 0
    for i in range(number_of_node):
        edges = []
        edges2 = []
        input_edges = []
        output_edges = []
        num_of_edges = 0
        flag = 0
        buffers = []
        temp1 = {}
        temp2 = {}
        temp3 = {}
        temp4 = {}
        counter = 0
        dirName = '../../packet_transaction_lib/src/src_' + str(i)
        os.makedirs(dirName, exist_ok=True)

        for process in processes:
            if process['source_file'] == str(i):
                for port in process:
                    if isinstance(process[port], dict):
                        if process[port]['direction'] == 'INP':
                            temp3 = {}
                            temp3['name'] = process[port]['name']
                            buffers.append(temp3)
                        num_of_edges += 1
                        temp1 = {}
                        temp2 = {}
                        temp1['name'] = process[port]['name']
                        for edge in edges:
                            flag = 0
                            if edge['name'] == temp1['name']:
                                if process[port]['direction'] == 'INP':
                                    temp4 = {}
                                    temp4['proc_num'] = process[
                                        'process_name'].split('_')[1]
                                    temp4['port_num'] = process[port]['ID']
                                    temp4['name'] = process[port]['name']
                                    input_edges.append(temp4)
                                num_of_edges -= 1
                                flag = 1
                                continue
                        if flag == 1:
                            continue
                        edges.append(temp1)
                        # edges['name'] = process[port]['name']
                        if process[port]['direction'] == 'INP':
                            temp2['proc_num'] = process['process_name'].split(
                                '_')[1]
                            temp2['port_num'] = process[port]['ID']
                            temp2['name'] = process[port]['name']
                            input_edges.append(temp2)
                        elif process[port]['direction'] == 'OUT':
                            temp2['proc_num'] = process['process_name'].split(
                                '_')[1]
                            temp2['port_num'] = process[port]['ID']
                            temp2['name'] = process[port]['name']
                            output_edges.append(temp2)

        counter = 0
        flag = 0
        edges2 = []
        temp = {}
        for process in processes:
            if process['source_file'] == str(i):
                for port in process:
                    if isinstance(process[port], dict):
                        temp = {}
                        temp['num_of_inp_token'] = None
                        temp['num_of_out_token'] = None
                        temp['counter'] = counter
                        counter += 1
                        temp['name'] = process[port]['name']

                        for edge in edges2:
                            flag = 0
                            if edge['name'] == temp['name']:
                                if process[port]['direction'] == 'INP':
                                    edge['num_of_inp_token'] = 'P' + process[
                                        'process_name'].split(
                                            '_')[1] + '_INP' + process[port][
                                                'ID'] + '_NUM_OF_TOKEN'
                                    edge['size_of_token_type'] = 'P' + process[
                                        'process_name'].split(
                                            '_')[1] + '_INP' + process[port][
                                                'ID'] + '_TYPE'
                                    edge['buffer'] = process[port]['name']
                                elif process[port]['direction'] == 'OUT':
                                    edge['num_of_out_token'] = 'P' + process[
                                        'process_name'].split(
                                            '_')[1] + '_OUT' + process[port][
                                                'ID'] + '_NUM_OF_TOKEN'
                                counter -= 1
                                flag = 1
                                continue
                        if flag == 1:
                            continue

                        temp['proc_src'] = process[port]['name'].split(
                            '_')[0][1]
                        temp['proc_dest'] = process[port]['name'].split(
                            '_')[1][1]
                        if process[port]['direction'] == 'INP':
                            temp['num_of_inp_token'] = 'P' + process[
                                'process_name'].split(
                                    '_')[1] + '_INP' + process[port][
                                        'ID'] + '_NUM_OF_TOKEN'
                            temp['size_of_token_type'] = 'P' + process[
                                'process_name'].split('_')[
                                    1] + '_INP' + process[port]['ID'] + '_TYPE'
                            temp['node_dest'] = process['source_file']
                            temp['buffer'] = process[port]['name']
                        if process[port]['direction'] == 'OUT':
                            temp['num_of_out_token'] = 'P' + process[
                                'process_name'].split(
                                    '_')[1] + '_OUT' + process[port][
                                        'ID'] + '_NUM_OF_TOKEN'
                            temp['size_of_token_type'] = 'P' + process[
                                'process_name'].split('_')[
                                    1] + '_OUT' + process[port]['ID'] + '_TYPE'
                            temp['node_src'] = process['source_file']
                        for process2 in processes:
                            for port2 in process2:
                                if isinstance(process2[port2], dict):
                                    if process2[port2]['name'] == temp[
                                            'name'] and process[
                                                'process_name'] != process2[
                                                    'process_name']:
                                        if process2[port2][
                                                'direction'] == 'INP':
                                            temp['node_dest'] = process2[
                                                'source_file']
                                        elif process2[port2][
                                                'direction'] == 'OUT':
                                            temp['node_src'] = process2[
                                                'source_file']
                        temp['external'] = 0
                        for process2 in processes:
                            for port2 in process2:
                                if isinstance(process2[port2], dict):
                                    if process2[port2]['name'] == temp[
                                            'name'] and process[
                                                'source_file'] != process2[
                                                    'source_file']:
                                        temp['external'] = 1
                        edges2.append(temp)

        loader = FileLoader('')
        template = loader.load_template(
            'Templates/packet_transaction_util_template.c')
        with open('../../packet_transaction_lib/src/src_' + str(i) +
                  '/packet_transaction_util.c',
                  'w',
                  encoding='utf-8') as f:
            L = [
                '#include "packet_transaction_util.h"\n',
                '#include "packet_transaction.h"\n\n'
            ]
            f.writelines(L)
            f.write(template.render(locals()))
Esempio n. 15
0
 def __init__(self, basedir):
     if not os.path.isabs(basedir):
         basedir = os.path.abspath(basedir)
     self.loader = FileLoader(basedir)
     self.basedir = basedir
Esempio n. 16
0
    for utterance_row in utterance_reader:
        temp_obj = TranscriptItem(get_sec(utterance_row[0]), utterance_row[0], utterance_row[1], utterance_row[2], "TEC")
        master_list.append(temp_obj)

    return sorted(master_list, key=get_key, reverse=False)


output_file_name_and_path = "./_webroot/A14FJ_remaining.html"
output_file = open(output_file_name_and_path, "w")
output_file.write("")
output_file.close()

output_file = open(output_file_name_and_path, "a")

# WRITE HEADER
template_loader = FileLoader('templates')
item_template = template_loader.load_template('template_afj_header.html')
output_file.write(item_template.render({'datarow': 0}, loader=template_loader).encode('utf-8'))

cur_row = 0
# input_file_path = "../MISSION_DATA/A17 master TEC and PAO utterances.csv"
# utterance_reader = csv.reader(open(input_file_path, "rU"), delimiter='|')
combined_list = get_combined_transcript_list()

timestamp_start_int = 913950

for combined_list_item in combined_list:
    timeid = "timeid" + combined_list_item.timestamp.translate(None, ":")
    if combined_list_item.timestamp != "":  # if not a TAPE change or title row
        if int(combined_list_item.timestamp.translate(None, ":")) >= timestamp_start_int:
            cur_row += 1
Esempio n. 17
0
# ----------------------------
def main():
    moduleManager.loadmodulelist('WebManager', configreader.globalconf)

    try:
        server = ThreadedHTTPServer(
            ('', int(configreader.webconf['httpport'])), HttpRequestHandler)
        if (configreader.webconf['usessl'] == 'yes'):
            # If ssl is activated, wrap the socket with SSL layer
            server.socket = ssl.wrap_socket(
                server.socket,
                keyfile=configreader.webconf['keyfile'],
                certfile=configreader.webconf['certfile'],
                server_side=True)
        print 'started httpserver...'
        server.serve_forever()
    except KeyboardInterrupt:
        print '^C received, shutting down server'
        server.socket.close()


# -------------------------------------
# Create global objects and run main()
# -------------------------------------
if __name__ == '__main__':
    # Create global objects that will be shared with all thread
    moduleManager = ModuleImporter(configreader.moduleconf)
    tplloader = FileLoader(configreader.webconf['templatesdir'])
    sessionmanager = SessionManager()
    main()
Esempio n. 18
0
def gen():

    tree = ET.parse('../UserFiles/hw_conf.xml')
    root = tree.getroot()

    project_properties = {
        'DEVICE_FAMILY': root[0][0].text,
        'DEVICE': root[0][1].text
    }
    NoC = {
        'RowNo': root[1][0].text,
        'ColNo': root[1][1].text,
        'AddrWidth': root[1][2].text,
        'DataWidth': root[1][3].text,
        'PackWidth': root[1][4].text,
        'PhyCh': root[1][5].text,
        'PhyChAddr': root[1][6].text,
        'PhyRoCh': root[1][7].text,
        'PhyRoChAddr': root[1][8].text,
        'RoCh': root[1][9].text,
        'RoChAddr': root[1][10].text,
        'ViCh': root[1][11].text,
        'ViChAddr': root[1][12].text
    }

    tiles = []
    processors = []
    numOfTiles = int(NoC['RowNo']) * int(NoC['ColNo'])

    RowNoList = []
    ColNoList = []
    for i in range(0, int(NoC['RowNo'])):
        RowNoList.insert(i, i)
    for i in range(0, int(NoC['ColNo'])):
        ColNoList.insert(i, i)

    # must change
    # needs to insert the number of processors in Project-Properties
    numOfProcessors = numOfTiles

    # default values for tiles
    for j in range(0, int(NoC['RowNo'])):
        for i in range(0, int(NoC['ColNo'])):
            tiles.insert(
                j * int(NoC['ColNo']) + i, {
                    'j': j,
                    'i': i,
                    'number': j * int(NoC['ColNo']) + i,
                    'node_type': 'processor',
                    'node_name': 'NIOS II/e',
                    'memory_size': '32768.0',
                    'fifo_in_depth': '16',
                    'fifo_out_depth': '16'
                })

    # default values for processors
    for i in range(0, numOfProcessors):
        processors.insert(
            i, {
                'number': str(i),
                'node_type': 'processor',
                'node_name': 'NIOS II/e',
                'memory_size': '16384.0',
                'fifo_in_depth': '16',
                'fifo_out_depth': '16'
            })

    # change the values of tiles and processors, if it needs
    for tile in root[2]:
        if tile[0].text == "processor":
            for child in tile:
                processors[int(
                    tile[0].attrib['number'])][child.tag] = child.text
        for child in tile:
            tiles[int(tile.attrib['number'])][child.tag] = child.text

    loader = FileLoader('Templates')

    # generate qsys_system.tcl
    template = loader.load_template('qsys_system.tcl')
    with open("../hw_scripts/qsys_system.tcl", 'w', encoding='utf-8') as f:
        f.write(template.render(locals()))

    # generate NoC.vhd
    template = loader.load_template('NOC.vhd')
    with open("../hw_sources/NOC.vhd", 'w', encoding='utf-8') as f:
        f.write(template.render(locals()))

    # generate NoC_hw.tcl
    template = loader.load_template('NoC_hw.tcl')
    with open("../hw_scripts/NoC_hw.tcl", 'w', encoding='utf-8') as f:
        f.write(template.render(locals()))

    # generate synth_qsys.tcl
    template = loader.load_template('synth_qsys.tcl')
    with open("../hw_scripts/synth_qsys.tcl", 'w', encoding='utf-8') as f:
        f.write(template.render(locals()))

    # generate wrapper.v
    template = loader.load_template('constraints.tcl')
    with open("../hw_scripts/constraints.tcl", 'w', encoding='utf-8') as f:
        f.write(template.render(locals()))

    # generate wrapper.v
    template = loader.load_template('wrapper.v')
    with open("../hw_sources/wrapper.v", 'w', encoding='utf-8') as f:
        f.write(template.render(locals()))
Esempio n. 19
0
def gen():
    src = r'../../UserFiles/process_codes'
    dest = r'../../templateEngine/applicationEngine'

    os.chdir(src)
    for file in glob.glob("*"):
        copyfile(src + "\\" + file, dest + "\\" + file)
    os.chdir('../../templateEngine/applicationEngine')
    xmlTree = ET.parse('../../UserFiles/hw_conf.xml')
    root = xmlTree.getroot()

    number_of_node = int(root[1][0].text) * int(root[1][1].text)

    xmlTree = ET.parse('../../UserFiles/application.xml')
    root = xmlTree.getroot()

    processes = []

    for element in root:
        if element.tag == 'process':
            temp = {}
            temp['process_name'] = element.get('name').split('_')[1]
            temp['numOfInp'] = element.get('numOfInp')
            temp['numOfOut'] = element.get('numOfOut')
            for subElement in element:
                temp2 = {}
                if subElement.tag == 'port':
                    temp2['ID'] = subElement.get('ID')
                    temp2['name'] = subElement.get('name')
                    temp2['type'] = subElement.get('type')
                    temp2['direction'] = subElement.get('direction')
                    temp2['direction_lowercase'] = subElement.get('direction').lower()
                    temp2['numOfToken'] = subElement.get('numOfToken')
                    temp2['process_name'] = element.get('name').split('_')[1]
                    if subElement.get('direction') == 'INP':
                        if subElement.get('init_val') != '':
                            k = 0
                            init_arr = []
                            for init_vall in subElement.get('init_val').split(','):
                                init_temp = {}
                                init_temp['index'] = k
                                init_temp['value'] = subElement.get('init_val').split(',')[k]
                                init_arr.append(init_temp)
                                k +=1
                            temp2.update({'initial_val': init_arr})
                            # temp2['init_val'] = subElement.get('init_val')
                    temp.update({subElement.get('name'): temp2})
                elif subElement.tag == 'source_file':
                    temp.update({'source_file': subElement.get('name').split('_')[1]})
            processes.append(temp)

    i = 0
    nodePR = []
    ports = []
    for i in range(number_of_node):
        nodePR = []
        ports = []
        for process in processes:
            if process['source_file'] == str(i):
                nodePR.append(process)
                for port in process:
                    if isinstance(process[port], dict):
                        ports.append(process[port])
        loader = FileLoader('')
        template = loader.load_template('Templates/node_template.c')
        with open('../../sw_sources/node_' + str(i) + '.c', 'w',encoding='utf-8') as f:
            L = ['#include "sys/alt_stdio.h"\n',
                 '#include "altera_avalon_fifo_regs.h"\n',
                 '#include "altera_avalon_fifo_util.h"\n',
                 '#include "sys/alt_irq.h"\n',
                 '#include <stdio.h>\n',
                 '#include <stdint.h>\n',
                 '#include "packet_transaction_util.h"\n',
                 '#include <unistd.h>\n\n',
                 '#define ALMOST_EMPTY 2\n',
                 '#define ALMOST_FULL 11\n']
            f.writelines(L)
            f.write(template.render(locals(), loader))
Esempio n. 20
0
        tiles.insert(j*int(NoC['ColNo'])+i, {'j': j, 'i': i, 'number': j*int(NoC['ColNo'])+i    , 'node_type': 'processor', 'node_name': 'NIOS II/e', 'memory_size': '16384.0',
                         'fifo_in_depth': '16', 'fifo_out_depth': '16'})

# default values for processors
for i in range(0, numOfProcessors):
    processors.insert(i, {'number': str(i), 'node_type': 'processor', 'node_name': 'NIOS II/e', 'memory_size': '16384.0', 'fifo_in_depth': '16', 'fifo_out_depth': '16'})

# change the values of tiles and processors, if it needs
for tile in root[2]:
    if tile[0].text == "processor":
        for child in tile:
            processors[int(tile[0].attrib['number'])][child.tag] = child.text
    for child in tile:
        tiles[int(tile.attrib['number'])][child.tag] = child.text

loader = FileLoader('Templates')

# generate qsys_system.tcl
template = loader.load_template('qsys_system.tcl')
with open("../../hw_scripts/qsys_system.tcl", 'w', encoding = 'utf-8') as f:
    f.write(template.render(locals()))

# generate NoC.vhd
template = loader.load_template('NOC.vhd')
with open("../../hw_sources/NOC.vhd", 'w', encoding = 'utf-8') as f:
    f.write(template.render(locals()))

# generate NoC_hw.tcl
template = loader.load_template('NoC_hw.tcl')
with open("../../hw_scripts/NoC_hw.tcl", 'w', encoding = 'utf-8') as f:
    f.write(template.render(locals()))
Esempio n. 21
0
def get_loader():
    return FileLoader(os.getcwd())
Esempio n. 22
0
from os.path import isfile, getsize
from mimetypes import guess_type
from datetime import datetime
from quik import FileLoader
from db import *
import threading

loader = FileLoader('')


def get_size(resource):
    file_size = 0
    if isfile(resource):
        file_size = getsize(resource)
    return file_size


def get_mime_type(file):

    mime_type = b'text/html'

    if get_size(file) > 0:
        (mime_type, encoding) = guess_type(file)
        mime_type = mime_type.encode('ASCII')
    return mime_type


def gen_status(file_size):

    status = b'HTTP/1.1 '
Esempio n. 23
0
def main() :
    parser = argparse.ArgumentParser(description='Read data from REGO2000')
    parser.add_argument('-m', '--mode', default='json')
    parser.add_argument('-c', '--configfile', required=True)
    parser.add_argument('-s', '--configsection', required=True)
    parser.add_argument('-p', '--path', required=True)
    parser.add_argument('-x', '--explore', action='store_true', help='use the list of starting points in <path> to fetch and enumerate all available URLs')
    args = parser.parse_args()

    config = configparser.SafeConfigParser()
    config.read(args.configfile)
    host = config.get(args.configsection, 'host');
    vendorkey = config.get(args.configsection, 'vendorkey');
    devicepassword = config.get(args.configsection, 'devicepassword');
    userpassword = config.get(args.configsection, 'userpassword');
    key = makeKey(vendorkey, devicepassword, userpassword)
    htmltemplate = config.get(args.configsection, 'htmltemplate');

    if args.explore :
        startpaths = args.path.split(',')
        leaves = []
        while startpaths :
            sp = startpaths.pop().strip()
            sys.stderr.write("Trying " + sp + "\n")
            try :
                res = json.loads(get(host, sp, key).decode())
                if res["type"] == "refEnum" :
                    for nsp in res["references"] :
                        startpaths.append(nsp["id"])
                elif "value" in res :
                    leaves.append("scalar:" + sp)
                elif "values" in res :
                    leaves.append("vector:" + sp)
                else :
                    leaves.append("unknown:" + sp)
            except:
                sys.stderr.write('Caught exception\n')
                pass
        leaves.sort()
        for leaf in leaves :
            print(leaf)
                    
    else :
        try:
            data = get(host, args.path, key)

            if args.mode == 'raw':
                print(data)
            elif args.mode == 'string':
                print(data.decode())
            elif args.mode == 'json':
                pdata = json.loads(data.decode())
                print(json.dumps(pdata, sort_keys=True, indent=4))
            elif args.mode == 'value':
                pdata = json.loads(data.decode())
                print(pdata["value"])
            elif args.mode == 'values':
                pdata = json.loads(data.decode())
                print(json.dumps(pdata["values"], sort_keys=True, indent=4))
            elif args.mode == 'errcodes':
                ecfile = config.get(args.configsection, 'errcodes');
                with open(ecfile) as data_file:
                    errcodes = json.load(data_file)
                pdata = json.loads(data.decode())
                notifications=[]
                for v in pdata["values"] :
                    note={}
                    note["orig"] = v
                    if str(v["ccd"]) in errcodes :
                        note["explanation"] = errcodes[str(v["ccd"])]
                    notifications.append(note)
                loader = FileLoader('')
                template = loader.load_template(htmltemplate)
                if notifications : 
                    print (template.render(locals(), loader=loader))
                else :
                    print ('<html><head></head><body><h1>No active notifications</h1></body></html>');
        except:
            print ('N/A')
            pass
Esempio n. 24
0
File: main.py Progetto: tasaif/febe
#!/usr/bin/env python

import web
import os
from quik import FileLoader
loader = FileLoader('html')


class Template:
    def GET(self, path):
        user_data = web.input()
        template = loader.load_template("../template/" + path)
        return template.render(user_data, loader=loader).encode('utf-8')


urls = (
    '/template/(.*)',
    'Template',
)
app = web.application(urls, globals())

if __name__ == "__main__":
    app.run()
Esempio n. 25
0
 def render(self, template_name, *args, **kwargs):
     loader = FileLoader(self.template_dirs[0])
     template = loader.load_template(template_name)
     return template.render(kwargs, loader=loader).encode('utf-8')