<commit_before>#-----------------------------------------------------------------------------
# Title      : Autotuning System for Xilinx MGTs
# Project    :
#-----------------------------------------------------------------------------
# File       : run.py
# Author     : Vitor Finotti Ferreira
# Company    :
# Created    : 2017-07-12
# Last update: 2017-07-12
# Standard   : Python 3.4
#-----------------------------------------------------------------------------
# Description:
#
# Autotuning script for the KC705 GTX transceivers
#
#-----------------------------------------------------------------------------
# Copyright (c) 2017 Vitor Finotti Ferreira
#-----------------------------------------------------------------------------
# Revisions  :
# Date        Version  Author          Description
# 2017-Jul-12 1.0      vfinotti        Created
#-----------------------------------------------------------------------------

from classes.pyIBERT import pyIBERT
import time
import os
from configparser import SafeConfigParser

# Load init
config = SafeConfigParser()
config.read('config.ini')
server0_addr = config.get('hw_server','server0_addr')
server0_port = config.get('hw_server','server0_port')
target0_name = config.get('hw_server','target0_name')
target0_freq = config.get('hw_server','target0_freq')
server1_addr = config.get('hw_server','server1_addr')
server1_port = config.get('hw_server','server1_port')
target1_name = config.get('hw_server','target1_name')
target1_freq = config.get('hw_server','target1_freq')
mgt = config.get('mgt_parameters','mgt')
TXDIFFSWING = config.get('mgt_parameters','TXDIFFSWING')
TXPOST = config.get('mgt_parameters','TXPOST')
TXPRE = config.get('mgt_parameters','TXPRE')
RXTERM = config.get('mgt_parameters','RXTERM')
tcl_dir = config.get('test','tcl_dir')
tcl_transm_name = config.get('test','tcl_transm_name')
tcl_rcv_name = config.get('test','tcl_rcv_name')
results_dir = config.get('test','results_dir')
results_name = config.get('test','results_name')
desired_area = config.get('test','desired_area')

mgt = mgt.replace(",\n",",")
mgt = mgt.split(",")
TXDIFFSWING = TXDIFFSWING.replace(",\n",",")
TXDIFFSWING = TXDIFFSWING.split(",")
TXPOST = TXPOST.replace(",\n",",")
TXPOST = TXPOST.split(",")
TXPRE = TXPRE.replace(",\n",",")
TXPRE = TXPRE.split(",")
RXTERM = RXTERM.replace(",\n",",")
RXTERM = RXTERM.split(",")

# Main script
print("----------------------------------------------------------------------")
print("Creating Instance 0")
rcv = pyIBERT(server0_addr,server0_port,target0_name,target0_freq)
print("Creating Instance 1")
transm = pyIBERT(server1_addr,server1_port,target1_name,target1_freq)

rcv.source("./" + tcl_dir + tcl_rcv_name + ".tcl")
transm.source("./" + tcl_dir + tcl_transm_name + ".tcl")

for mgt_idx in range(len(mgt)):

    f = open("./" + results_dir + results_name + mgt[mgt_idx] + ".csv","w")
    f.write("TXDIFFSWING"
            + "," + "TXPRE"
            + "," + "TXPOST"
            + "," + "RXTERM"
            + "," + "Open Area"
            + "\n")
    obj = "get_hw_sio_links *MGT_" + mgt[mgt_idx] + "/RX"

    rcv.scan_remove_all()
    transm.scan_remove_all()

    iter = 0

    best_area = "-1"
    best_diff = TXDIFFSWING[0]
    best_rx = RXTERM[0]
    best_txpost = TXPOST[0]
    best_txpre = TXPRE[0]

    for i in TXDIFFSWING[::4]:
        transm.set_property("TXDIFFSWING", i, obj)
        for j in TXPRE[::4]:
            transm.set_property("TXPRE", j, obj)
            for k in TXPOST[::4]:
                transm.set_property("TXPOST", k, obj)
                for l in RXTERM[::1]:
                    rcv.set_property("RXTERM", l, obj)

                    transm.sendCommand("set_property PORT.GTTXRESET 1 [get_hw_sio_links -of_objects [get_hw_sio_linkgroups {LINKGROUP_0}]]")
                    transm.sendCommand("commit_hw_sio [get_hw_sio_links -of_objects [get_hw_sio_linkgroups {LINKGROUP_0}]]")
                    transm.sendCommand("set_property PORT.GTTXRESET 0 [get_hw_sio_links -of_objects [get_hw_sio_linkgroups {LINKGROUP_0}]]")
                    transm.sendCommand("commit_hw_sio [get_hw_sio_links -of_objects [get_hw_sio_linkgroups {LINKGROUP_0}]]")
                    rcv.sendCommand("set_property PORT.GTRXRESET 1 [get_hw_sio_links -of_objects [get_hw_sio_linkgroups {LINKGROUP_0}]]")
                    rcv.sendCommand("commit_hw_sio [get_hw_sio_links -of_objects [get_hw_sio_linkgroups {LINKGROUP_0}]]")
                    rcv.sendCommand("set_property PORT.GTRXRESET 0 [get_hw_sio_links -of_objects [get_hw_sio_linkgroups {LINKGROUP_0}]]")
                    rcv.sendCommand("commit_hw_sio [get_hw_sio_links -of_objects [get_hw_sio_linkgroups {LINKGROUP_0}]]")

                    print("------ DFE_8gbps - " + mgt[mgt_idx])
                    print("------ Iter: " + str(iter))
                    print(iter)
                    iter = iter+1

                    rcv.reset_sio_link_error(obj)
                    rcv.refresh_hw_sio(obj)
                    time.sleep(6) # parameters are not instantly refreshed
                    link = rcv.get_property("LOGIC.LINK", obj)

                    if link == "1":
                        err = rcv.get_property("LOGIC.ERRBIT_COUNT", obj)

                        if int(err,16) == 0: # convert str hex to int

                            rcv.scan_create("xil_scan", obj)
                            rcv.scan_set_all("6", "6", "1e-9")
                            rcv.scan_run_all()

                            scan_area = rcv.get_property("Open_Area", "get_hw_sio_scan")
                            #scan_ber = rcv.get_property("RX_BER", obj)
                            rcv.scan_remove_all()
                            f.write(i
                                    + "," +  j
                                    + "," +  k
                                    + "," +  l
                                    + "," +  scan_area
                                    + "\n")

                            if int(float(scan_area)) > int(float(best_area)):
                                best_area = scan_area
                                best_diff = i
                                best_txpre = j
                                best_txpost = k
                                best_rx = l
                    if int(float(best_area)) > desired_area:
                        break
                if int(float(best_area)) > desired_area:
                    break
            if int(float(best_area)) > desired_area:
                break
        if int(float(best_area)) > desired_area:
            break

    transm.set_property("TXDIFFSWING", best_diff, obj)
    transm.set_property("TXPRE", best_txpre, obj)
    transm.set_property("TXPOST", best_txpost, obj)
    rcv.set_property("RXTERM", best_rx, obj)

    print("exit main()")

    f.write("------------BEST------------\n")
    f.write(best_diff
            + "," +  best_txpre
            + "," +  best_txpost
            + "," +  best_rx
            + "," +  best_area
            + "\n")

    f.close()

    print("End of " + mgt[mgt_idx])

rcv.sendCommand("close_hw")
transm.sendCommand("close_hw")

rcv.terminate()
transm.terminate()
<commit_msg>Adding function to create directory<commit_after>#-----------------------------------------------------------------------------
# Title      : Autotuning System for Xilinx MGTs
# Project    :
#-----------------------------------------------------------------------------
# File       : run.py
# Author     : Vitor Finotti Ferreira
# Company    :
# Created    : 2017-07-12
# Last update: 2017-07-12
# Standard   : Python 3.4
#-----------------------------------------------------------------------------
# Description:
#
# Autotuning script for the KC705 GTX transceivers
#
#-----------------------------------------------------------------------------
# Copyright (c) 2017 Vitor Finotti Ferreira
#-----------------------------------------------------------------------------
# Revisions  :
# Date        Version  Author          Description
# 2017-Jul-12 1.0      vfinotti        Created
#-----------------------------------------------------------------------------

from classes.pyIBERT import pyIBERT
import time
import os
from configparser import SafeConfigParser

# Functions
def create_dir(dir):
    # checks if data subdirectory exists. If not, create it.
    os.makedirs(os.getcwd() + "/" + os.path.dirname(dir), exist_ok=True)

# Load init
config = SafeConfigParser()
config.read('config.ini')
server0_addr = config.get('hw_server','server0_addr')
server0_port = config.get('hw_server','server0_port')
target0_name = config.get('hw_server','target0_name')
target0_freq = config.get('hw_server','target0_freq')
server1_addr = config.get('hw_server','server1_addr')
server1_port = config.get('hw_server','server1_port')
target1_name = config.get('hw_server','target1_name')
target1_freq = config.get('hw_server','target1_freq')
mgt = config.get('mgt_parameters','mgt')
TXDIFFSWING = config.get('mgt_parameters','TXDIFFSWING')
TXPOST = config.get('mgt_parameters','TXPOST')
TXPRE = config.get('mgt_parameters','TXPRE')
RXTERM = config.get('mgt_parameters','RXTERM')
tcl_dir = config.get('test','tcl_dir')
tcl_transm_name = config.get('test','tcl_transm_name')
tcl_rcv_name = config.get('test','tcl_rcv_name')
results_dir = config.get('test','results_dir')
results_name = config.get('test','results_name')
desired_area = config.get('test','desired_area')

mgt = mgt.replace(",\n",",")
mgt = mgt.split(",")
TXDIFFSWING = TXDIFFSWING.replace(",\n",",")
TXDIFFSWING = TXDIFFSWING.split(",")
TXPOST = TXPOST.replace(",\n",",")
TXPOST = TXPOST.split(",")
TXPRE = TXPRE.replace(",\n",",")
TXPRE = TXPRE.split(",")
RXTERM = RXTERM.replace(",\n",",")
RXTERM = RXTERM.split(",")

# Main script
print("----------------------------------------------------------------------")
print("Creating Instance 0")
rcv = pyIBERT(server0_addr,server0_port,target0_name,target0_freq)
print("Creating Instance 1")
transm = pyIBERT(server1_addr,server1_port,target1_name,target1_freq)

rcv.source("./" + tcl_dir + tcl_rcv_name + ".tcl")
transm.source("./" + tcl_dir + tcl_transm_name + ".tcl")

create_dir(results_dir)

for mgt_idx in range(len(mgt)):

    f = open("./" + results_dir + results_name + mgt[mgt_idx] + ".csv","w")
    f.write("TXDIFFSWING"
            + "," + "TXPRE"
            + "," + "TXPOST"
            + "," + "RXTERM"
            + "," + "Open Area"
            + "\n")
    obj = "get_hw_sio_links *MGT_" + mgt[mgt_idx] + "/RX"

    rcv.scan_remove_all()
    transm.scan_remove_all()

    iter = 0

    best_area = "-1"
    best_diff = TXDIFFSWING[0]
    best_rx = RXTERM[0]
    best_txpost = TXPOST[0]
    best_txpre = TXPRE[0]

    for i in TXDIFFSWING[::4]:
        transm.set_property("TXDIFFSWING", i, obj)
        for j in TXPRE[::4]:
            transm.set_property("TXPRE", j, obj)
            for k in TXPOST[::4]:
                transm.set_property("TXPOST", k, obj)
                for l in RXTERM[::1]:
                    rcv.set_property("RXTERM", l, obj)

                    transm.sendCommand("set_property PORT.GTTXRESET 1 [get_hw_sio_links -of_objects [get_hw_sio_linkgroups {LINKGROUP_0}]]")
                    transm.sendCommand("commit_hw_sio [get_hw_sio_links -of_objects [get_hw_sio_linkgroups {LINKGROUP_0}]]")
                    transm.sendCommand("set_property PORT.GTTXRESET 0 [get_hw_sio_links -of_objects [get_hw_sio_linkgroups {LINKGROUP_0}]]")
                    transm.sendCommand("commit_hw_sio [get_hw_sio_links -of_objects [get_hw_sio_linkgroups {LINKGROUP_0}]]")
                    rcv.sendCommand("set_property PORT.GTRXRESET 1 [get_hw_sio_links -of_objects [get_hw_sio_linkgroups {LINKGROUP_0}]]")
                    rcv.sendCommand("commit_hw_sio [get_hw_sio_links -of_objects [get_hw_sio_linkgroups {LINKGROUP_0}]]")
                    rcv.sendCommand("set_property PORT.GTRXRESET 0 [get_hw_sio_links -of_objects [get_hw_sio_linkgroups {LINKGROUP_0}]]")
                    rcv.sendCommand("commit_hw_sio [get_hw_sio_links -of_objects [get_hw_sio_linkgroups {LINKGROUP_0}]]")

                    print("------ DFE_8gbps - " + mgt[mgt_idx])
                    print("------ Iter: " + str(iter))
                    print(iter)
                    iter = iter+1

                    rcv.reset_sio_link_error(obj)
                    rcv.refresh_hw_sio(obj)
                    time.sleep(6) # parameters are not instantly refreshed
                    link = rcv.get_property("LOGIC.LINK", obj)

                    if link == "1":
                        err = rcv.get_property("LOGIC.ERRBIT_COUNT", obj)

                        if int(err,16) == 0: # convert str hex to int

                            rcv.scan_create("xil_scan", obj)
                            rcv.scan_set_all("6", "6", "1e-9")
                            rcv.scan_run_all()

                            scan_area = rcv.get_property("Open_Area", "get_hw_sio_scan")
                            #scan_ber = rcv.get_property("RX_BER", obj)
                            rcv.scan_remove_all()
                            f.write(i
                                    + "," +  j
                                    + "," +  k
                                    + "," +  l
                                    + "," +  scan_area
                                    + "\n")

                            if int(float(scan_area)) > int(float(best_area)):
                                best_area = scan_area
                                best_diff = i
                                best_txpre = j
                                best_txpost = k
                                best_rx = l
                    if int(float(best_area)) > desired_area:
                        break
                if int(float(best_area)) > desired_area:
                    break
            if int(float(best_area)) > desired_area:
                break
        if int(float(best_area)) > desired_area:
            break

    transm.set_property("TXDIFFSWING", best_diff, obj)
    transm.set_property("TXPRE", best_txpre, obj)
    transm.set_property("TXPOST", best_txpost, obj)
    rcv.set_property("RXTERM", best_rx, obj)

    print("exit main()")

    f.write("------------BEST------------\n")
    f.write(best_diff
            + "," +  best_txpre
            + "," +  best_txpost
            + "," +  best_rx
            + "," +  best_area
            + "\n")

    f.close()

    print("End of " + mgt[mgt_idx])

rcv.sendCommand("close_hw")
transm.sendCommand("close_hw")

rcv.terminate()
transm.terminate()
<|endoftext|>


<commit_before>#-----------------------------------------------------------------------------
# Title      : Autotuning System for Xilinx MGTs
# Project    :
#-----------------------------------------------------------------------------
# File       : run.py
# Author     : Vitor Finotti Ferreira
# Company    :
# Created    : 2017-07-12
# Last update: 2017-07-12
# Standard   : Python 3.4
#-----------------------------------------------------------------------------
# Description:
#
# Autotuning script for the KC705 GTX transceivers
#
#-----------------------------------------------------------------------------
# Copyright (c) 2017 Vitor Finotti Ferreira
#-----------------------------------------------------------------------------
# Revisions  :
# Date        Version  Author          Description
# 2017-Jul-12 1.0      vfinotti        Created
#-----------------------------------------------------------------------------

from classes.pyIBERT import pyIBERT
import time
import os
from configparser import SafeConfigParser

# Functions
def create_dir(dir):
    # checks if data subdirectory exists. If not, create it.
    os.makedirs(os.getcwd() + "/" + os.path.dirname(dir), exist_ok=True)

def format_to_list(data):
    data = data.replace(",\n",",")
    data = data.split(",")
    return data

# Load init
config = SafeConfigParser()
config.read('config.ini')
server0_addr = config.get('hw_server','server0_addr')
server0_port = config.get('hw_server','server0_port')
target0_name = config.get('hw_server','target0_name')
target0_freq = config.get('hw_server','target0_freq')
server1_addr = config.get('hw_server','server1_addr')
server1_port = config.get('hw_server','server1_port')
target1_name = config.get('hw_server','target1_name')
target1_freq = config.get('hw_server','target1_freq')
mgt = config.get('mgt_parameters','mgt')
TXDIFFSWING = config.get('mgt_parameters','TXDIFFSWING')
TXPOST = config.get('mgt_parameters','TXPOST')
TXPRE = config.get('mgt_parameters','TXPRE')
RXTERM = config.get('mgt_parameters','RXTERM')
tcl_dir = config.get('test','tcl_dir')
tcl_transm_name = config.get('test','tcl_transm_name')
tcl_rcv_name = config.get('test','tcl_rcv_name')
results_dir = config.get('test','results_dir')
results_name = config.get('test','results_name')
desired_area = config.getint('test','desired_area')

mgt = format_to_list(mgt)
TXDIFFSWING = format_to_list(TXDIFFSWING)
TXPOST = format_to_list(TXPOST)
TXPRE = format_to_list(TXPRE)
RXTERM = format_to_list(RXTERM)

# Main script
print("----------------------------------------------------------------------")
print("Creating Instance 0")
rcv = pyIBERT(server0_addr,server0_port,target0_name,target0_freq)
print("Creating Instance 1")
transm = pyIBERT(server1_addr,server1_port,target1_name,target1_freq)

rcv.source("./" + tcl_dir + tcl_rcv_name + ".tcl")
transm.source("./" + tcl_dir + tcl_transm_name + ".tcl")

create_dir(results_dir)

for mgt_idx in range(len(mgt)):

    f = open("./" + results_dir + results_name + mgt[mgt_idx] + ".csv","w")
    f.write("TXDIFFSWING"
            + "," + "TXPRE"
            + "," + "TXPOST"
            + "," + "RXTERM"
            + "," + "Open Area"
            + "\n")
    obj = "get_hw_sio_links *MGT_" + mgt[mgt_idx] + "/RX"

    rcv.scan_remove_all()
    transm.scan_remove_all()

    iter = 0

    best_area = "-1"
    best_diff = TXDIFFSWING[0]
    best_rx = RXTERM[0]
    best_txpost = TXPOST[0]
    best_txpre = TXPRE[0]

    for i in TXDIFFSWING[::4]:
        transm.set_property("TXDIFFSWING", i, obj)
        for j in TXPRE[::4]:
            transm.set_property("TXPRE", j, obj)
            for k in TXPOST[::4]:
                transm.set_property("TXPOST", k, obj)
                for l in RXTERM[::1]:
                    rcv.set_property("RXTERM", l, obj)

                    transm.sendCommand("set_property PORT.GTTXRESET 1 [get_hw_sio_links -of_objects [get_hw_sio_linkgroups {LINKGROUP_0}]]")
                    transm.sendCommand("commit_hw_sio [get_hw_sio_links -of_objects [get_hw_sio_linkgroups {LINKGROUP_0}]]")
                    transm.sendCommand("set_property PORT.GTTXRESET 0 [get_hw_sio_links -of_objects [get_hw_sio_linkgroups {LINKGROUP_0}]]")
                    transm.sendCommand("commit_hw_sio [get_hw_sio_links -of_objects [get_hw_sio_linkgroups {LINKGROUP_0}]]")
                    rcv.sendCommand("set_property PORT.GTRXRESET 1 [get_hw_sio_links -of_objects [get_hw_sio_linkgroups {LINKGROUP_0}]]")
                    rcv.sendCommand("commit_hw_sio [get_hw_sio_links -of_objects [get_hw_sio_linkgroups {LINKGROUP_0}]]")
                    rcv.sendCommand("set_property PORT.GTRXRESET 0 [get_hw_sio_links -of_objects [get_hw_sio_linkgroups {LINKGROUP_0}]]")
                    rcv.sendCommand("commit_hw_sio [get_hw_sio_links -of_objects [get_hw_sio_linkgroups {LINKGROUP_0}]]")

                    print("------ DFE_8gbps - " + mgt[mgt_idx])
                    print("------ Iter: " + str(iter))
                    print(iter)
                    iter = iter+1

                    rcv.reset_sio_link_error(obj)
                    rcv.refresh_hw_sio(obj)
                    time.sleep(6) # parameters are not instantly refreshed
                    link = rcv.get_property("LOGIC.LINK", obj)

                    if link == "1":
                        err = rcv.get_property("LOGIC.ERRBIT_COUNT", obj)

                        if int(err,16) == 0: # convert str hex to int

                            rcv.scan_create("xil_scan", obj)
                            rcv.scan_set_all("6", "6", "1e-9")
                            rcv.scan_run_all()

                            scan_area = rcv.get_property("Open_Area", "get_hw_sio_scan")
                            #scan_ber = rcv.get_property("RX_BER", obj)
                            rcv.scan_remove_all()
                            f.write(i
                                    + "," +  j
                                    + "," +  k
                                    + "," +  l
                                    + "," +  scan_area
                                    + "\n")

                            if int(float(scan_area)) > int(float(best_area)):
                                best_area = scan_area
                                best_diff = i
                                best_txpre = j
                                best_txpost = k
                                best_rx = l
                    if int(float(best_area)) > desired_area:
                        break
                if int(float(best_area)) > desired_area:
                    break
            if int(float(best_area)) > desired_area:
                break
        if int(float(best_area)) > desired_area:
            break

    transm.set_property("TXDIFFSWING", best_diff, obj)
    transm.set_property("TXPRE", best_txpre, obj)
    transm.set_property("TXPOST", best_txpost, obj)
    rcv.set_property("RXTERM", best_rx, obj)

    print("exit main()")

    f.write("------------BEST------------\n")
    f.write(best_diff
            + "," +  best_txpre
            + "," +  best_txpost
            + "," +  best_rx
            + "," +  best_area
            + "\n")

    f.close()

    print("End of " + mgt[mgt_idx])

rcv.sendCommand("close_hw")
transm.sendCommand("close_hw")

rcv.terminate()
transm.terminate()
<commit_msg>Changing message to be printed after every iteration<commit_after>#-----------------------------------------------------------------------------
# Title      : Autotuning System for Xilinx MGTs
# Project    :
#-----------------------------------------------------------------------------
# File       : run.py
# Author     : Vitor Finotti Ferreira
# Company    :
# Created    : 2017-07-12
# Last update: 2017-07-12
# Standard   : Python 3.4
#-----------------------------------------------------------------------------
# Description:
#
# Autotuning script for the KC705 GTX transceivers
#
#-----------------------------------------------------------------------------
# Copyright (c) 2017 Vitor Finotti Ferreira
#-----------------------------------------------------------------------------
# Revisions  :
# Date        Version  Author          Description
# 2017-Jul-12 1.0      vfinotti        Created
#-----------------------------------------------------------------------------

from classes.pyIBERT import pyIBERT
import time
import os
from configparser import SafeConfigParser

# Functions
def create_dir(dir):
    # checks if data subdirectory exists. If not, create it.
    os.makedirs(os.getcwd() + "/" + os.path.dirname(dir), exist_ok=True)

def format_to_list(data):
    data = data.replace(",\n",",")
    data = data.split(",")
    return data

# Load init
config = SafeConfigParser()
config.read('config.ini')
server0_addr = config.get('hw_server','server0_addr')
server0_port = config.get('hw_server','server0_port')
target0_name = config.get('hw_server','target0_name')
target0_freq = config.get('hw_server','target0_freq')
server1_addr = config.get('hw_server','server1_addr')
server1_port = config.get('hw_server','server1_port')
target1_name = config.get('hw_server','target1_name')
target1_freq = config.get('hw_server','target1_freq')
mgt = config.get('mgt_parameters','mgt')
TXDIFFSWING = config.get('mgt_parameters','TXDIFFSWING')
TXPOST = config.get('mgt_parameters','TXPOST')
TXPRE = config.get('mgt_parameters','TXPRE')
RXTERM = config.get('mgt_parameters','RXTERM')
tcl_dir = config.get('test','tcl_dir')
tcl_transm_name = config.get('test','tcl_transm_name')
tcl_rcv_name = config.get('test','tcl_rcv_name')
results_dir = config.get('test','results_dir')
results_name = config.get('test','results_name')
desired_area = config.getint('test','desired_area')

mgt = format_to_list(mgt)
TXDIFFSWING = format_to_list(TXDIFFSWING)
TXPOST = format_to_list(TXPOST)
TXPRE = format_to_list(TXPRE)
RXTERM = format_to_list(RXTERM)

# Main script
print("----------------------------------------------------------------------")
print("Creating Instance 0")
rcv = pyIBERT(server0_addr,server0_port,target0_name,target0_freq)
print("Creating Instance 1")
transm = pyIBERT(server1_addr,server1_port,target1_name,target1_freq)

rcv.source("./" + tcl_dir + tcl_rcv_name + ".tcl")
transm.source("./" + tcl_dir + tcl_transm_name + ".tcl")

create_dir(results_dir)

for mgt_idx in range(len(mgt)):

    f = open("./" + results_dir + results_name + mgt[mgt_idx] + ".csv","w")
    f.write("TXDIFFSWING"
            + "," + "TXPRE"
            + "," + "TXPOST"
            + "," + "RXTERM"
            + "," + "Open Area"
            + "\n")
    obj = "get_hw_sio_links *MGT_" + mgt[mgt_idx] + "/RX"

    rcv.scan_remove_all()
    transm.scan_remove_all()

    iter = 0

    best_area = "-1"
    best_diff = TXDIFFSWING[0]
    best_rx = RXTERM[0]
    best_txpost = TXPOST[0]
    best_txpre = TXPRE[0]

    for i in TXDIFFSWING[::4]:
        transm.set_property("TXDIFFSWING", i, obj)
        for j in TXPRE[::4]:
            transm.set_property("TXPRE", j, obj)
            for k in TXPOST[::4]:
                transm.set_property("TXPOST", k, obj)
                for l in RXTERM[::1]:
                    rcv.set_property("RXTERM", l, obj)

                    transm.sendCommand("set_property PORT.GTTXRESET 1 [get_hw_sio_links -of_objects [get_hw_sio_linkgroups {LINKGROUP_0}]]")
                    transm.sendCommand("commit_hw_sio [get_hw_sio_links -of_objects [get_hw_sio_linkgroups {LINKGROUP_0}]]")
                    transm.sendCommand("set_property PORT.GTTXRESET 0 [get_hw_sio_links -of_objects [get_hw_sio_linkgroups {LINKGROUP_0}]]")
                    transm.sendCommand("commit_hw_sio [get_hw_sio_links -of_objects [get_hw_sio_linkgroups {LINKGROUP_0}]]")
                    rcv.sendCommand("set_property PORT.GTRXRESET 1 [get_hw_sio_links -of_objects [get_hw_sio_linkgroups {LINKGROUP_0}]]")
                    rcv.sendCommand("commit_hw_sio [get_hw_sio_links -of_objects [get_hw_sio_linkgroups {LINKGROUP_0}]]")
                    rcv.sendCommand("set_property PORT.GTRXRESET 0 [get_hw_sio_links -of_objects [get_hw_sio_linkgroups {LINKGROUP_0}]]")
                    rcv.sendCommand("commit_hw_sio [get_hw_sio_links -of_objects [get_hw_sio_linkgroups {LINKGROUP_0}]]")

                    print("------ Transceiver - " + mgt[mgt_idx])
                    print("------ Iter: " + str(iter))
                    print(iter)
                    iter = iter+1

                    rcv.reset_sio_link_error(obj)
                    rcv.refresh_hw_sio(obj)
                    time.sleep(6) # parameters are not instantly refreshed
                    link = rcv.get_property("LOGIC.LINK", obj)

                    if link == "1":
                        err = rcv.get_property("LOGIC.ERRBIT_COUNT", obj)

                        if int(err,16) == 0: # convert str hex to int

                            rcv.scan_create("xil_scan", obj)
                            rcv.scan_set_all("6", "6", "1e-9")
                            rcv.scan_run_all()

                            scan_area = rcv.get_property("Open_Area", "get_hw_sio_scan")
                            #scan_ber = rcv.get_property("RX_BER", obj)
                            rcv.scan_remove_all()
                            f.write(i
                                    + "," +  j
                                    + "," +  k
                                    + "," +  l
                                    + "," +  scan_area
                                    + "\n")

                            if int(float(scan_area)) > int(float(best_area)):
                                best_area = scan_area
                                best_diff = i
                                best_txpre = j
                                best_txpost = k
                                best_rx = l
                    if int(float(best_area)) > desired_area:
                        break
                if int(float(best_area)) > desired_area:
                    break
            if int(float(best_area)) > desired_area:
                break
        if int(float(best_area)) > desired_area:
            break

    transm.set_property("TXDIFFSWING", best_diff, obj)
    transm.set_property("TXPRE", best_txpre, obj)
    transm.set_property("TXPOST", best_txpost, obj)
    rcv.set_property("RXTERM", best_rx, obj)

    print("exit main()")

    f.write("------------BEST------------\n")
    f.write(best_diff
            + "," +  best_txpre
            + "," +  best_txpost
            + "," +  best_rx
            + "," +  best_area
            + "\n")

    f.close()

    print("End of " + mgt[mgt_idx])

rcv.sendCommand("close_hw")
transm.sendCommand("close_hw")

rcv.terminate()
transm.terminate()
<|endoftext|>


<commit_before>import os
import requests
import zipfile
import json

from cStringIO import StringIO
from datetime import datetime
from slyd.gitstorage.repoman import Repoman

from slybot.validation.schema import get_schema_validator

DASH_API_URL = None

def set_dash_url(dash_url):
    global DASH_API_URL
    DASH_API_URL = dash_url

class DeployError(Exception):
    pass

def import_project(name, apikey):
    """Download a project from Dash and create a GIT repo for it."""
    archive = zipfile.ZipFile(StringIO(_download_project(name, apikey)))
    repo = Repoman.create_repo(name)
    files = {}
    for filename in archive.namelist():
        contents = archive.read(filename)
        if filename == 'items.json':
            resource = 'items'
            contents = _fix_items(contents)
        elif filename == 'extractors.json':
            resource = 'extractors'
        elif filename.startswith('spiders'):
            resource = 'spider'
        else:
            resource = None
        if resource in ['items', 'spider', 'extractors']:
            # Validate against slybot schemas.
            get_schema_validator(resource).validate(json.loads(contents))
        files[filename] = contents
    repo.save_files(files, 'master', 'Initial import.')
    return repo

def deploy_project(name, apikey):
    """Archive a GIT project and upload it to Dash."""
    zbuff = StringIO()
    _archive_project(name, zbuff)
    zbuff.reset()
    payload = {'apikey': apikey, 'project': name}
    req = requests.post(DASH_API_URL + 'as/import.json',
        files=[('archive', ('archive', zbuff, 'application/zip'))],
        params=payload)
    if req.status_code == 200:
        project_url = DASH_API_URL.rsplit('/', 2)[0] + '/p/' + name
        return {
            'status': 'ok',
            'schedule_url': project_url,
        }
    else:
        raise DeployError('Deploy to Dash failed: %s' % req.text)

def _fix_items(raw_items):
    """Fixes issues with the imported items."""
    items = json.loads(raw_items)
    for _, item in items.iteritems():
        if 'url' in item['fields']:
            del item['fields']['url']
    return json.dumps(items)

def _download_project(name, apikey):
    """Download a zipped project from Dash."""
    payload = {'apikey': apikey, 'project': name, 'version': 'slybot'}
    r = requests.get(DASH_API_URL + 'as/project-slybot.zip', params=payload)
    return r.content

def _add_to_archive(archive, filename, contents, tstamp):
    """Add a file to a zip archive."""
    fileinfo = zipfile.ZipInfo(filename, tstamp)
    fileinfo.external_attr = 0666 << 16L
    archive.writestr(fileinfo, contents, zipfile.ZIP_DEFLATED)

def _archive_project(name, buff):
    """Archive a project stored in GIT into a zip file."""
    repo = Repoman.open_repo(name)
    now = datetime.now().timetuple()[:6]
    archive = zipfile.ZipFile(buff, "w", zipfile.ZIP_DEFLATED)
    for file_path in repo.list_files_for_branch('master'):
        file_contents = repo.file_contents_for_branch(file_path, 'master')
        _add_to_archive(archive, file_path, file_contents, now)
    archive.close()
<commit_msg>Give names to templates when importing from dash<commit_after>import os
import requests
import zipfile
import json

from cStringIO import StringIO
from datetime import datetime
from slyd.gitstorage.repoman import Repoman

from slybot.validation.schema import get_schema_validator

DASH_API_URL = None

def set_dash_url(dash_url):
    global DASH_API_URL
    DASH_API_URL = dash_url

class DeployError(Exception):
    pass

def import_project(name, apikey):
    """Download a project from Dash and create a GIT repo for it."""
    archive = zipfile.ZipFile(StringIO(_download_project(name, apikey)))
    repo = Repoman.create_repo(name)
    files = {}
    for filename in archive.namelist():
        contents = archive.read(filename)
        if filename == 'items.json':
            resource = 'items'
        elif filename == 'extractors.json':
            resource = 'extractors'
        elif filename.startswith('spiders'):
            resource = 'spider'
        else:
            resource = None
        if resource in ['items', 'spider', 'extractors']:
            as_json = json.loads(contents)
            if resource == 'items':
                as_json = _fix_items(as_json)
            elif resource == 'spider':
                as_json = _fix_spider(as_json)
            # Validate against slybot schemas.
            get_schema_validator(resource).validate(as_json)
            contents = json.dumps(as_json)
        files[filename] = contents
    repo.save_files(files, 'master', 'Initial import.')
    return repo

def deploy_project(name, apikey):
    """Archive a GIT project and upload it to Dash."""
    zbuff = StringIO()
    _archive_project(name, zbuff)
    zbuff.reset()
    payload = {'apikey': apikey, 'project': name}
    req = requests.post(DASH_API_URL + 'as/import.json',
        files=[('archive', ('archive', zbuff, 'application/zip'))],
        params=payload)
    if req.status_code == 200:
        project_url = DASH_API_URL.rsplit('/', 2)[0] + '/p/' + name
        return {
            'status': 'ok',
            'schedule_url': project_url,
        }
    else:
        raise DeployError('Deploy to Dash failed: %s' % req.text)

def _fix_items(items):
    """Fixes issues with the imported items."""
    for _, item in items.iteritems():
        if 'url' in item['fields']:
            del item['fields']['url']
    return items

def _fix_spider(spider):
    for template in spider['templates']:
        template['name'] = template['page_id']
    return spider

def _download_project(name, apikey):
    """Download a zipped project from Dash."""
    payload = {'apikey': apikey, 'project': name, 'version': 'slybot'}
    r = requests.get(DASH_API_URL + 'as/project-slybot.zip', params=payload)
    return r.content

def _add_to_archive(archive, filename, contents, tstamp):
    """Add a file to a zip archive."""
    fileinfo = zipfile.ZipInfo(filename, tstamp)
    fileinfo.external_attr = 0666 << 16L
    archive.writestr(fileinfo, contents, zipfile.ZIP_DEFLATED)

def _archive_project(name, buff):
    """Archive a project stored in GIT into a zip file."""
    repo = Repoman.open_repo(name)
    now = datetime.now().timetuple()[:6]
    archive = zipfile.ZipFile(buff, "w", zipfile.ZIP_DEFLATED)
    for file_path in repo.list_files_for_branch('master'):
        file_contents = repo.file_contents_for_branch(file_path, 'master')
        _add_to_archive(archive, file_path, file_contents, now)
    archive.close()
<|endoftext|>


<commit_before>from module import Module

class SubMod1(Module):
	#Constructor
	def __init__(self):
		Module.__init__(self, 'submod1')

	#Resets module
	def resetModule(self):
		self.changeStateIncomplete()
		self.input = 0

	#Runs module minigame
	def submod1main(self):
		#No input yet
		if(self.input == 0):
			pass
		else:
			#Win if enter 1, strike otherwise.
			if(self.input == '1'):
				self.changeStateComplete()
			#Other inputs cause strike
			else:
				self.changeStateStrike()
			print('Submod1 current state: ' + self.getState())
			'''print('Reset')
			self.resetModule()
			print('Submod1 current state: ' + self.getState())'''
<commit_msg>Once submodule is complete won't run anymore, tests work out so far!<commit_after>from module import Module

class SubMod1(Module):
	#Constructor
	def __init__(self):
		Module.__init__(self, 'submod1')

	#Resets module
	def resetModule(self):
		self.changeStateIncomplete()
		self.input = 0

	#Runs module minigame
	def submod1main(self):
		if self.getState() == 'COMPLETE':
			pass
		else:
			#No input yet
			if(self.input == 0):
				pass
			else:
				#Win if enter 1, strike otherwise.
				if(self.input == '1'):
					self.changeStateComplete()
				#Other inputs cause strike
				else:
					self.changeStateStrike()
				print('Submod1 current state: ' + self.getState())
<|endoftext|>


<commit_before>from module import Module
from PyQt5 import QtWidgets, QtGui
from random import randint

class SubMod5(Module):
	#Constructor
	def __init__(self, frame):
		Module.__init__(self, frame, 'submod5')

		self.init = 1
		self.stage = 0
		self.selectedButton = 1

		self.label = QtWidgets.QLabel()
		self.outline1 = QtWidgets.QLabel()
		self.outline2 = QtWidgets.QLabel()
		self.outline3 = QtWidgets.QLabel()
		self.outline4 = QtWidgets.QLabel()
		#self.label.setGeometry(10,10,100,200)
		self.button1 = QtWidgets.QPushButton()
		self.button2 = QtWidgets.QPushButton()
		self.button3 = QtWidgets.QPushButton()
		self.button4 = QtWidgets.QPushButton()
		self.select1 = QtWidgets.QLabel()
		self.select2 = QtWidgets.QLabel()
		self.select3 = QtWidgets.QLabel()
		self.select4 = QtWidgets.QLabel()
		grid = QtWidgets.QGridLayout()
		self.setLayout(grid)

		grid.addWidget(self.label, 0, 0, 100, 100)
		grid.addWidget(self.outline1, 2, 2)
		grid.addWidget(self.outline2, 2, 3)
		grid.addWidget(self.outline3, 3, 2)
		grid.addWidget(self.outline4, 3, 3)
		grid.addWidget(self.button1, 2, 2)
		grid.addWidget(self.button2, 2, 3)
		grid.addWidget(self.button3, 3, 2)
		grid.addWidget(self.button4, 3, 3)
		grid.addWidget(self.select1, 2, 1)
		grid.addWidget(self.select2, 2, 4)
		grid.addWidget(self.select3, 3, 1)
		grid.addWidget(self.select4, 3, 4)

		reader = QtGui.QImageReader("moduleBox.png")
		image = reader.read()
		qpixmap = QtGui.QPixmap()
		qpixmap.convertFromImage(image)
		self.label.setPixmap(qpixmap)

		reader = QtGui.QImageReader("buttonBox.png")
		image = reader.read()
		qpixmap = QtGui.QPixmap()
		qpixmap.convertFromImage(image)
		self.outline1.setPixmap(qpixmap)
		self.outline2.setPixmap(qpixmap)
		self.outline3.setPixmap(qpixmap)
		self.outline4.setPixmap(qpixmap)

	def resetModule(self):
		self.changeStateIncomplete()
		self.instruction_index = 0
		self.input = 0

	def correctAns(self):
		if self.init ==0:
			self.stage += 1
			self.init = 1
			self.selectedButton = 1
			print ("stage1reach")
		else:
			pass

	def incorrectAns(self):
		self.changeStateStrike()
		print ("stage1strike")

	def checkAns0(self):
		if self.posGen == 1:
			if self.selectedButton == 1:
				self.correctAns()
			else:
				self.incorrectAns()
		if self.posGen == 2:
			if self.selectedButton == 2:
				self.correctAns()
			else:
				self.incorrectAns()
		if self.posGen == 3:
			if self.selectedButton == 3:
				self.correctAns()
			else:
				self.incorrectAns()
		if self.posGen == 4:
			if self.selectedButton == 4:
				self.correctAns()
			else:
				self.incorrectAns()

	def checkAns1(self):
		if self.posGen == 1:
			if self.selectedButton == 2:
				self.correctAns()
			else:
				self.incorrectAns()
		if self.posGen == 2:
			if self.selectedButton == 3:
				self.correctAns()
			else:
				self.incorrectAns()
		if self.posGen == 3:
			if self.selectedButton == 4:
				self.correctAns()
			else:
				self.incorrectAns()
		if self.posGen == 4:
			if self.selectedButton == 1:
				self.correctAns()
			else:
				self.incorrectAns()

	def checkAns2(self):
		if self.posGen == 1:
			if self.selectedButton == 3:
				self.correctAns()
			else:
				self.incorrectAns()
		if self.posGen == 2:
			if self.selectedButton == 4:
				self.correctAns()
			else:
				self.incorrectAns()
		if self.posGen == 3:
			if self.selectedButton == 1:
				self.correctAns()
			else:
				self.incorrectAns()
		if self.posGen == 4:
			if self.selectedButton == 2:
				self.correctAns()
			else:
				self.incorrectAns()

	def checkAns3(self):
		if self.posGen == 1:
			if self.selectedButton == 4:
				self.correctAns()
			else:
				self.incorrectAns()
		if self.posGen == 2:
			if self.selectedButton == 1:
				self.correctAns()
			else:
				self.incorrectAns()
		if self.posGen == 3:
			if self.selectedButton == 2:
				self.correctAns()
			else:
				self.incorrectAns()
		if self.posGen == 4:
			if self.selectedButton == 3:
				self.correctAns()
			else:
				self.incorrectAns()

	def main(self):
		if self.getState() == 'COMPLETE':
			pass
		else:
			#No input yet
			if(False):
				pass
			else:
				if self.init == 1:

					self.symbolGen = randint(1,6)
					self.posGen = randint(1,4)
					if self.symbolGen == 1:
						if self.posGen == 1:
							self.button1.setText('[')
							self.button2.setText('<')
							self.button3.setText('3')
							self.button4.setText(']')
						if self.posGen == 2:
							self.button2.setText('[')
							self.button3.setText('<')
							self.button4.setText('3')
							self.button1.setText(']')
						if self.posGen == 3:
							self.button3.setText('[')
							self.button4.setText('<')
							self.button1.setText('3')
							self.button2.setText(']')
						if self.posGen == 4:
							self.button4.setText('[')
							self.button1.setText('<')
							self.button2.setText('3')
							self.button3.setText(']')
					elif self.symbolGen == 2:
						if self.posGen == 1:
							self.button1.setText('$')
							self.button2.setText('@')
							self.button3.setText('#')
							self.button4.setText('!')
						if self.posGen == 2:
							self.button2.setText('$')
							self.button3.setText('@')
							self.button4.setText('#')
							self.button1.setText('!')
						if self.posGen == 3:
							self.button3.setText('$')
							self.button4.setText('@')
							self.button1.setText('#')
							self.button2.setText('!')
						if self.posGen == 4:
							self.button4.setText('$')
							self.button1.setText('@')
							self.button2.setText('#')
							self.button3.setText('!')
					elif self.symbolGen == 3:
						if self.posGen == 1:
							self.button1.setText('^')
							self.button2.setText('&')
							self.button3.setText('%')
							self.button4.setText('*')
						if self.posGen == 2:
							self.button2.setText('^')
							self.button3.setText('&')
							self.button4.setText('%')
							self.button1.setText('*')
						if self.posGen == 3:
							self.button3.setText('^')
							self.button4.setText('&')
							self.button1.setText('%')
							self.button2.setText('*')
						if self.posGen == 4:
							self.button4.setText('^')
							self.button1.setText('&')
							self.button2.setText('%')
							self.button3.setText('*')
					elif self.symbolGen == 4:
						if self.posGen == 1:
							self.button1.setText('<')
							self.button2.setText('~')
							self.button3.setText('>')
							self.button4.setText(',')
						if self.posGen == 2:
							self.button2.setText('<')
							self.button3.setText('~')
							self.button4.setText('>')
							self.button1.setText(',')
						if self.posGen == 3:
							self.button3.setText('<')
							self.button4.setText('~')
							self.button1.setText('>')
							self.button2.setText(',')
						if self.posGen == 4:
							self.button4.setText('<')
							self.button1.setText('~')
							self.button2.setText('>')
							self.button3.setText(',')
					elif self.symbolGen == 5:
						if self.posGen == 1:
							self.button1.setText(':')
							self.button2.setText('&')
							self.button3.setText('=')
							self.button4.setText('{')
						if self.posGen == 2:
							self.button2.setText(':')
							self.button3.setText('&')
							self.button4.setText('=')
							self.button1.setText('{')
						if self.posGen == 3:
							self.button3.setText(':')
							self.button4.setText('&')
							self.button1.setText('=')
							self.button2.setText('{')
						if self.posGen == 4:
							self.button4.setText(':')
							self.button1.setText('&')
							self.button2.setText('=')
							self.button3.setText('{')
					elif self.symbolGen == 6:
						if self.posGen == 1:
							self.button1.setText('/')
							self.button2.setText('+')
							self.button3.setText('#')
							self.button4.setText('?')
						if self.posGen == 2:
							self.button2.setText('/')
							self.button3.setText('+')
							self.button4.setText('#')
							self.button1.setText('?')
						if self.posGen == 3:
							self.button3.setText('/')
							self.button4.setText('+')
							self.button1.setText('#')
							self.button2.setText('?')
						if self.posGen == 4:
							self.button4.setText('/')
							self.button1.setText('+')
							self.button2.setText('#')
							self.button3.setText('?')
				else:
					if selectedButton == 1:
						if self.input == 'RIGHT':
							self.selectedButton == 2
						if self.input == 'DOWN':
							self.selectedButton == 3
						else:
							pass
					elif selectedButton == 2:
						if self.input == 'LEFT':
							self.selectedButton == 1
						if self.input == 'DOWN':
							self.selectedButton == 4
						else:
							pass
					elif selectedButton == 3:
						if self.input == 'RIGHT':
							self.selectedButton == 4
						if self.input == 'UP':
							self.selectedButton == 1
						else:
							pass
					elif selectedButton == 4:
						if self.input == 'LEFT':
							self.selectedButton == 3
						if self.input == 'UP':
							self.selectedButton == 2
						else:
							pass

					if self.selectedButton == 1:
						if self.selectedButton == 1:
							self.select1.setText(">")
							self.select1.show()
							self.select2.hide()
							self.select3.hide()
						elif self.selectedButton == 2:
							self.select2.setText("<")
							self.select2.show()
							self.select1.hide()
							self.select3.hide()
						elif self.selectedButton == 3:
							self.select3.show()
							self.select3.setText(">")
							self.select2.hide()
							self.select1.hide()
						elif self.selectedButton == 4:
							self.select2.setText("<")
							self.select2.show()
							self.select1.hide()
							self.select3.hide()

					if self.input == 'BUTTONA':
						if self.stage == 0:
							if self.symbolGen == 1:
								self.checkAns0()
							elif self.symbolGen == 2:
								self.checkAns0()
							elif self.symbolGen == 3:
								self.checkAns0()
							elif self.symbolGen == 4:
								self.checkAns0()
							elif self.symbolGen == 5:
								self.checkAns0()
							elif self.symbolGen == 6:
								self.checkAns0()

						if self.stage == 1:
							if self.symbolGen == 1:
								self.checkAns1()
							elif self.symbolGen == 2:
								self.checkAns1()
							elif self.symbolGen == 3:
								self.checkAns1()
							elif self.symbolGen == 4:
								self.checkAns1()
							elif self.symbolGen == 5:
								self.checkAns1()
							elif self.symbolGen == 6:
								self.checkAns1()

						if self.stage == 2:
							if self.symbolGen == 1:
								self.checkAns2()
							elif self.symbolGen == 2:
								self.checkAns2()
							elif self.symbolGen == 3:
								self.checkAns2()
							elif self.symbolGen == 4:
								self.checkAns2()
							elif self.symbolGen == 5:
								self.checkAns2()
							elif self.symbolGen == 6:
								self.checkAns2()

						if self.stage == 3:
							if self.symbolGen == 1:
								self.checkAns3()
							elif self.symbolGen == 2:
								self.checkAns3()
							elif self.symbolGen == 3:
								self.checkAns3()
							elif self.symbolGen == 4:
								self.checkAns3()
							elif self.symbolGen == 5:
								self.checkAns3()
							elif self.symbolGen == 6:
								self.checkAns3()

						if self.stage == 4:
							self.changeStateComplete()

			#ADDED THIS SO INPUT WOULDN'T STAY, NEED TO FIX!
			self.input = 0
<commit_msg>revert<commit_after>from module import Module
from PyQt5 import QtWidgets, QtGui
from random import randint

class SubMod5(Module):
	#Constructor
	def __init__(self, frame):
		Module.__init__(self, frame, 'submod5')

		self.init = 1
		self.stage = 0
		self.selectedButton = 1

		self.label = QtWidgets.QLabel()
		self.outline1 = QtWidgets.QLabel()
		self.outline2 = QtWidgets.QLabel()
		self.outline3 = QtWidgets.QLabel()
		self.outline4 = QtWidgets.QLabel()
		#self.label.setGeometry(10,10,100,200)
		self.button1 = QtWidgets.QPushButton()
		self.button2 = QtWidgets.QPushButton()
		self.button3 = QtWidgets.QPushButton()
		self.button4 = QtWidgets.QPushButton()
		self.select1 = QtWidgets.QLabel()
		self.select2 = QtWidgets.QLabel()
		self.select3 = QtWidgets.QLabel()
		self.select4 = QtWidgets.QLabel()
		grid = QtWidgets.QGridLayout()
		self.setLayout(grid)

		grid.addWidget(self.label, 0, 0, 100, 100)
		grid.addWidget(self.outline1, 2, 2)
		grid.addWidget(self.outline2, 2, 3)
		grid.addWidget(self.outline3, 3, 2)
		grid.addWidget(self.outline4, 3, 3)
		grid.addWidget(self.button1, 2, 2)
		grid.addWidget(self.button2, 2, 3)
		grid.addWidget(self.button3, 3, 2)
		grid.addWidget(self.button4, 3, 3)
		grid.addWidget(self.select1, 2, 1)
		grid.addWidget(self.select2, 2, 4)
		grid.addWidget(self.select3, 3, 1)
		grid.addWidget(self.select4, 3, 4)

		reader = QtGui.QImageReader("moduleBox.png")
		image = reader.read()
		qpixmap = QtGui.QPixmap()
		qpixmap.convertFromImage(image)
		self.label.setPixmap(qpixmap)

		reader = QtGui.QImageReader("buttonBox.png")
		image = reader.read()
		qpixmap = QtGui.QPixmap()
		qpixmap.convertFromImage(image)
		self.outline1.setPixmap(qpixmap)
		self.outline2.setPixmap(qpixmap)
		self.outline3.setPixmap(qpixmap)
		self.outline4.setPixmap(qpixmap)

	def resetModule(self):
		self.changeStateIncomplete()
		self.instruction_index = 0
		self.input = 0

	def correctAns(self):

		self.stage += 1

		print ("stage1reach")

	def incorrectAns(self):
		self.changeStateStrike()
		print ("stage1strike")

	def checkAns0(self):
		if self.posGen == 1:
			if self.selectedButton == 1:
				self.correctAns()
			else:
				self.incorrectAns()
		if self.posGen == 2:
			if self.selectedButton == 2:
				self.correctAns()
			else:
				self.incorrectAns()
		if self.posGen == 3:
			if self.selectedButton == 3:
				self.correctAns()
			else:
				self.incorrectAns()
		if self.posGen == 4:
			if self.selectedButton == 4:
				self.correctAns()
			else:
				self.incorrectAns()

	def checkAns1(self):
		if self.posGen == 1:
			if self.selectedButton == 2:
				self.correctAns()
			else:
				self.incorrectAns()
		if self.posGen == 2:
			if self.selectedButton == 3:
				self.correctAns()
			else:
				self.incorrectAns()
		if self.posGen == 3:
			if self.selectedButton == 4:
				self.correctAns()
			else:
				self.incorrectAns()
		if self.posGen == 4:
			if self.selectedButton == 1:
				self.correctAns()
			else:
				self.incorrectAns()

	def checkAns2(self):
		if self.posGen == 1:
			if self.selectedButton == 3:
				self.correctAns()
			else:
				self.incorrectAns()
		if self.posGen == 2:
			if self.selectedButton == 4:
				self.correctAns()
			else:
				self.incorrectAns()
		if self.posGen == 3:
			if self.selectedButton == 1:
				self.correctAns()
			else:
				self.incorrectAns()
		if self.posGen == 4:
			if self.selectedButton == 2:
				self.correctAns()
			else:
				self.incorrectAns()

	def checkAns3(self):
		if self.posGen == 1:
			if self.selectedButton == 4:
				self.correctAns()
			else:
				self.incorrectAns()
		if self.posGen == 2:
			if self.selectedButton == 1:
				self.correctAns()
			else:
				self.incorrectAns()
		if self.posGen == 3:
			if self.selectedButton == 2:
				self.correctAns()
			else:
				self.incorrectAns()
		if self.posGen == 4:
			if self.selectedButton == 3:
				self.correctAns()
			else:
				self.incorrectAns()

	def main(self):
		if self.getState() == 'COMPLETE':
			pass
		else:
			#No input yet
			if(False):
				pass
			else:
				if self.init == 1:
					self.init = 0

					self.symbolGen = randint(1,6)
					self.posGen = randint(1,4)
					if self.symbolGen == 1:
						if self.posGen == 1:
							self.button1.setText('[')
							self.button2.setText('<')
							self.button3.setText('3')
							self.button4.setText(']')
						if self.posGen == 2:
							self.button2.setText('[')
							self.button3.setText('<')
							self.button4.setText('3')
							self.button1.setText(']')
						if self.posGen == 3:
							self.button3.setText('[')
							self.button4.setText('<')
							self.button1.setText('3')
							self.button2.setText(']')
						if self.posGen == 4:
							self.button4.setText('[')
							self.button1.setText('<')
							self.button2.setText('3')
							self.button3.setText(']')
					elif self.symbolGen == 2:
						if self.posGen == 1:
							self.button1.setText('$')
							self.button2.setText('@')
							self.button3.setText('#')
							self.button4.setText('!')
						if self.posGen == 2:
							self.button2.setText('$')
							self.button3.setText('@')
							self.button4.setText('#')
							self.button1.setText('!')
						if self.posGen == 3:
							self.button3.setText('$')
							self.button4.setText('@')
							self.button1.setText('#')
							self.button2.setText('!')
						if self.posGen == 4:
							self.button4.setText('$')
							self.button1.setText('@')
							self.button2.setText('#')
							self.button3.setText('!')
					elif self.symbolGen == 3:
						if self.posGen == 1:
							self.button1.setText('^')
							self.button2.setText('&')
							self.button3.setText('%')
							self.button4.setText('*')
						if self.posGen == 2:
							self.button2.setText('^')
							self.button3.setText('&')
							self.button4.setText('%')
							self.button1.setText('*')
						if self.posGen == 3:
							self.button3.setText('^')
							self.button4.setText('&')
							self.button1.setText('%')
							self.button2.setText('*')
						if self.posGen == 4:
							self.button4.setText('^')
							self.button1.setText('&')
							self.button2.setText('%')
							self.button3.setText('*')
					elif self.symbolGen == 4:
						if self.posGen == 1:
							self.button1.setText('<')
							self.button2.setText('~')
							self.button3.setText('>')
							self.button4.setText(',')
						if self.posGen == 2:
							self.button2.setText('<')
							self.button3.setText('~')
							self.button4.setText('>')
							self.button1.setText(',')
						if self.posGen == 3:
							self.button3.setText('<')
							self.button4.setText('~')
							self.button1.setText('>')
							self.button2.setText(',')
						if self.posGen == 4:
							self.button4.setText('<')
							self.button1.setText('~')
							self.button2.setText('>')
							self.button3.setText(',')
					elif self.symbolGen == 5:
						if self.posGen == 1:
							self.button1.setText(':')
							self.button2.setText('&')
							self.button3.setText('=')
							self.button4.setText('{')
						if self.posGen == 2:
							self.button2.setText(':')
							self.button3.setText('&')
							self.button4.setText('=')
							self.button1.setText('{')
						if self.posGen == 3:
							self.button3.setText(':')
							self.button4.setText('&')
							self.button1.setText('=')
							self.button2.setText('{')
						if self.posGen == 4:
							self.button4.setText(':')
							self.button1.setText('&')
							self.button2.setText('=')
							self.button3.setText('{')
					elif self.symbolGen == 6:
						if self.posGen == 1:
							self.button1.setText('/')
							self.button2.setText('+')
							self.button3.setText('#')
							self.button4.setText('?')
						if self.posGen == 2:
							self.button2.setText('/')
							self.button3.setText('+')
							self.button4.setText('#')
							self.button1.setText('?')
						if self.posGen == 3:
							self.button3.setText('/')
							self.button4.setText('+')
							self.button1.setText('#')
							self.button2.setText('?')
						if self.posGen == 4:
							self.button4.setText('/')
							self.button1.setText('+')
							self.button2.setText('#')
							self.button3.setText('?')
				else:
					if self.selectedButton == 1:
						if self.input == 'RIGHT':
							self.selectedButton = 2
						if self.input == 'DOWN':
							self.selectedButton = 3
						else:
							pass
					elif self.selectedButton == 2:
						if self.input == 'LEFT':
							self.selectedButton = 1
						if self.input == 'DOWN':
							self.selectedButton = 4
						else:
							pass
					elif self.selectedButton == 3:
						if self.input == 'RIGHT':
							self.selectedButton = 4
						if self.input == 'UP':
							self.selectedButton = 1
						else:
							pass
					elif self.selectedButton == 4:
						if self.input == 'LEFT':
							self.selectedButton = 3
						if self.input == 'UP':
							self.selectedButton = 2
						else:
							pass

					if self.selectedButton == 1:
						self.select1.setText(">")
						self.select1.show()
						self.select2.hide()
						self.select3.hide()
						self.select4.hide()
					elif self.selectedButton == 2:
						self.select2.setText("<")
						self.select2.show()
						self.select1.hide()
						self.select3.hide()
						self.select4.hide()
					elif self.selectedButton == 3:
						self.select4.hide()
						self.select3.setText(">")
						self.select3.show()
						self.select2.hide()
						self.select1.hide()
					elif self.selectedButton == 4:
						self.select4.setText("<")
						self.select4.show()
						self.select1.hide()
						self.select2.hide()
						self.select3.hide()

					if self.input == 'BUTTONA':
						if self.stage == 0:
							if self.symbolGen == 1:
								self.checkAns0()
							elif self.symbolGen == 2:
								self.checkAns0()
							elif self.symbolGen == 3:
								self.checkAns0()
							elif self.symbolGen == 4:
								self.checkAns0()
							elif self.symbolGen == 5:
								self.checkAns0()
							elif self.symbolGen == 6:
								self.checkAns0()

						elif self.stage == 1:
							if self.symbolGen == 1:
								self.checkAns1()
							elif self.symbolGen == 2:
								self.checkAns1()
							elif self.symbolGen == 3:
								self.checkAns1()
							elif self.symbolGen == 4:
								self.checkAns1()
							elif self.symbolGen == 5:
								self.checkAns1()
							elif self.symbolGen == 6:
								self.checkAns1()

						elif self.stage == 2:
							if self.symbolGen == 1:
								self.checkAns2()
							elif self.symbolGen == 2:
								self.checkAns2()
							elif self.symbolGen == 3:
								self.checkAns2()
							elif self.symbolGen == 4:
								self.checkAns2()
							elif self.symbolGen == 5:
								self.checkAns2()
							elif self.symbolGen == 6:
								self.checkAns2()

						elif self.stage == 3:
							if self.symbolGen == 1:
								self.checkAns3()
							elif self.symbolGen == 2:
								self.checkAns3()
							elif self.symbolGen == 3:
								self.checkAns3()
							elif self.symbolGen == 4:
								self.checkAns3()
							elif self.symbolGen == 5:
								self.checkAns3()
							elif self.symbolGen == 6:
								self.checkAns3()

						elif self.stage == 4:
							self.changeStateComplete()

			#ADDED THIS SO INPUT WOULDN'T STAY, NEED TO FIX!
			self.input = 0
<|endoftext|>


<commit_before># Copyright (c) 2009-2012, Andrew McNabb

from errno import EINTR
import os
import select
import signal
import sys
import threading

try:
    import queue
except ImportError:
    import Queue as queue

from psshlib.askpass_server import PasswordServer
from psshlib import psshutil

READ_SIZE = 1 << 16

class FatalError(RuntimeError):
    """A fatal error in the PSSH Manager."""
    pass

class Manager(object):
    """Executes tasks concurrently.

    Tasks are added with add_task() and executed in parallel with run().
    Returns a list of the exit statuses of the processes.

    Arguments:
        limit: Maximum number of commands running at once.
        timeout: Maximum allowed execution time in seconds.
    """
    def __init__(self, opts):
        self.limit = opts.par
        self.timeout = opts.timeout
        self.askpass = opts.askpass
        self.outdir = opts.outdir
        self.errdir = opts.errdir
        self.iomap = IOMap()

        self.taskcount = 0
        self.tasks = []
        self.running = []
        self.done = []

        self.askpass_socket = None

    def run(self):
        """Processes tasks previously added with add_task."""
        try:
            if self.outdir or self.errdir:
                writer = Writer(self.outdir, self.errdir)
                writer.start()
            else:
                writer = None

            if self.askpass:
                pass_server = PasswordServer()
                pass_server.start(self.iomap, self.limit)
                self.askpass_socket = pass_server.address

            self.set_sigchld_handler()

            try:
                self.update_tasks(writer)
                wait = None
                while self.running or self.tasks:
                    # Opt for efficiency over subsecond timeout accuracy.
                    if wait is None or wait < 1:
                        wait = 1
                    self.iomap.poll(wait)
                    self.update_tasks(writer)
                    wait = self.check_timeout()
            except KeyboardInterrupt:
                # This exception handler tries to clean things up and prints
                # out a nice status message for each interrupted host.
                self.interrupted()

        except KeyboardInterrupt:
            # This exception handler doesn't print out any fancy status
            # information--it just stops.
            pass

        if writer:
            writer.signal_quit()
            writer.join()

        statuses = [task.exitstatus for task in self.done]
        return statuses

    def clear_sigchld_handler(self):
        signal.signal(signal.SIGCHLD, signal.SIG_DFL)

    def set_sigchld_handler(self):
        # TODO: find out whether set_wakeup_fd still works if the default
        # signal handler is used (I'm pretty sure it doesn't work if the
        # signal is ignored).
        signal.signal(signal.SIGCHLD, self.handle_sigchld)
        # This should keep reads and writes from getting EINTR.
        if hasattr(signal, 'siginterrupt'):
            signal.siginterrupt(signal.SIGCHLD, False)

    def handle_sigchld(self, number, frame):
        """Apparently we need a sigchld handler to make set_wakeup_fd work."""
        # Write to the signal pipe (only for Python <2.5, where the
        # set_wakeup_fd method doesn't exist).
        if self.iomap.wakeup_writefd:
            os.write(self.iomap.wakeup_writefd, '\0')
        for task in self.running:
            if task.proc:
                task.proc.poll()
        # Apparently some UNIX systems automatically reset the SIGCHLD
        # handler to SIG_DFL.  Reset it just in case.
        self.set_sigchld_handler()

    def add_task(self, task):
        """Adds a Task to be processed with run()."""
        self.tasks.append(task)

    def update_tasks(self, writer):
        """Reaps tasks and starts as many new ones as allowed."""
        # Mask signals to work around a Python bug:
        #   http://bugs.python.org/issue1068268
        # Since sigprocmask isn't in the stdlib, clear the SIGCHLD handler.
        # Since signals are masked, reap_tasks needs to be called once for
        # each loop.
        keep_running = True
        while keep_running:
            self.clear_sigchld_handler()
            self._start_tasks_once(writer)
            self.set_sigchld_handler()
            keep_running = self.reap_tasks()

    def _start_tasks_once(self, writer):
        """Starts tasks once.

        Due to http://bugs.python.org/issue1068268, signals must be masked
        when this method is called.
        """
        while 0 < len(self.tasks) and len(self.running) < self.limit:
            task = self.tasks.pop(0)
            self.running.append(task)
            task.start(self.taskcount, self.iomap, writer, self.askpass_socket)
            self.taskcount += 1

    def reap_tasks(self):
        """Checks to see if any tasks have terminated.

        After cleaning up, returns the number of tasks that finished.
        """
        still_running = []
        finished_count = 0
        for task in self.running:
            if task.running():
                still_running.append(task)
            else:
                self.finished(task)
                finished_count += 1
        self.running = still_running
        return finished_count

    def check_timeout(self):
        """Kills timed-out processes and returns the lowest time left."""
        if self.timeout <= 0:
            return None

        min_timeleft = None
        for task in self.running:
            timeleft = self.timeout - task.elapsed()
            if timeleft <= 0:
                task.timedout()
                continue
            if min_timeleft is None or timeleft < min_timeleft:
                min_timeleft = timeleft

        if min_timeleft is None:
            return 0
        else:
            return max(0, min_timeleft)

    def interrupted(self):
        """Cleans up after a keyboard interrupt."""
        for task in self.running:
            task.interrupted()
            self.finished(task)

        for task in self.tasks:
            task.cancel()
            self.finished(task)

    def finished(self, task):
        """Marks a task as complete and reports its status to stdout."""
        self.done.append(task)
        n = len(self.done)
        task.report(n)

class IOMap(object):
    """A manager for file descriptors and their associated handlers.

    The poll method dispatches events to the appropriate handlers.
    """
    def __init__(self):
        self.readmap = {}
        self.writemap = {}

        # Setup the wakeup file descriptor to avoid hanging on lost signals.
        wakeup_readfd, wakeup_writefd = os.pipe()
        self.register_read(wakeup_readfd, self.wakeup_handler)
        # TODO: remove test when we stop supporting Python <2.5
        if hasattr(signal, 'set_wakeup_fd'):
            signal.set_wakeup_fd(wakeup_writefd)
            self.wakeup_writefd = None
        else:
            self.wakeup_writefd = wakeup_writefd

    def register_read(self, fd, handler):
        """Registers an IO handler for a file descriptor for reading."""
        self.readmap[fd] = handler

    def register_write(self, fd, handler):
        """Registers an IO handler for a file descriptor for writing."""
        self.writemap[fd] = handler

    def unregister(self, fd):
        """Unregisters the given file descriptor."""
        if fd in self.readmap:
            del self.readmap[fd]
        if fd in self.writemap:
            del self.writemap[fd]

    def poll(self, timeout=None):
        """Performs a poll and dispatches the resulting events."""
        if not self.readmap and not self.writemap:
            return
        rlist = list(self.readmap)
        wlist = list(self.writemap)
        try:
            rlist, wlist, _ = select.select(rlist, wlist, [], timeout)
        except select.error:
            _, e, _ = sys.exc_info()
            errno = e.args[0]
            if errno == EINTR:
                return
            else:
                raise
        for fd in rlist:
            handler = self.readmap[fd]
            handler(fd, self)
        for fd in wlist:
            handler = self.writemap[fd]
            handler(fd, self)

    def wakeup_handler(self, fd, iomap):
        """Handles read events on the signal wakeup pipe.

        This ensures that SIGCHLD signals aren't lost.
        """
        try:
            os.read(fd, READ_SIZE)
        except (OSError, IOError):
            _, e, _ = sys.exc_info()
            errno, message = e.args
            if errno != EINTR:
                sys.stderr.write('Fatal error reading from wakeup pipe: %s\n'
                        % message)
                raise FatalError

class Writer(threading.Thread):
    """Thread that writes to files by processing requests from a Queue.

    Until AIO becomes widely available, it is impossible to make a nonblocking
    write to an ordinary file.  The Writer thread processes all writing to
    ordinary files so that the main thread can work without blocking.
    """
    OPEN = object()
    EOF = object()
    ABORT = object()

    def __init__(self, outdir, errdir):
        threading.Thread.__init__(self)
        # A daemon thread automatically dies if the program is terminated.
        self.setDaemon(True)
        self.queue = queue.Queue()
        self.outdir = outdir
        self.errdir = errdir

        self.host_counts = {}
        self.files = {}

    def run(self):
        while True:
            filename, data = self.queue.get()
            if filename == self.ABORT:
                return

            if data == self.OPEN:
                self.files[filename] = open(filename, 'wb', buffering=1)
                psshutil.set_cloexec(self.files[filename])
            else:
                dest = self.files[filename]
                if data == self.EOF:
                    dest.close()
                else:
                    dest.write(data)
                    dest.flush()

    def open_files(self, host):
        """Called from another thread to create files for stdout and stderr.

        Returns a pair of filenames (outfile, errfile).  These filenames are
        used as handles for future operations.  Either or both may be None if
        outdir or errdir or not set.
        """
        outfile = errfile = None
        if self.outdir or self.errdir:
            count = self.host_counts.get(host, 0)
            self.host_counts[host] = count + 1
            if count:
                filename = "%s.%s" % (host, count)
            else:
                filename = host
            if self.outdir:
                outfile = os.path.join(self.outdir, filename)
                self.queue.put((outfile, self.OPEN))
            if self.errdir:
                errfile = os.path.join(self.errdir, filename)
                self.queue.put((errfile, self.OPEN))
        return outfile, errfile

    def write(self, filename, data):
        """Called from another thread to enqueue a write."""
        self.queue.put((filename, data))

    def close(self, filename):
        """Called from another thread to close the given file."""
        self.queue.put((filename, self.EOF))

    def signal_quit(self):
        """Called from another thread to request the Writer to quit."""
        self.queue.put((self.ABORT, None))

<commit_msg>Add support for select.poll on systems where it is available (issue #72)<commit_after># Copyright (c) 2009-2012, Andrew McNabb

from errno import EINTR
import os
import select
import signal
import sys
import threading

try:
    import queue
except ImportError:
    import Queue as queue

from psshlib.askpass_server import PasswordServer
from psshlib import psshutil

READ_SIZE = 1 << 16

class FatalError(RuntimeError):
    """A fatal error in the PSSH Manager."""
    pass

class Manager(object):
    """Executes tasks concurrently.

    Tasks are added with add_task() and executed in parallel with run().
    Returns a list of the exit statuses of the processes.

    Arguments:
        limit: Maximum number of commands running at once.
        timeout: Maximum allowed execution time in seconds.
    """
    def __init__(self, opts):
        self.limit = opts.par
        self.timeout = opts.timeout
        self.askpass = opts.askpass
        self.outdir = opts.outdir
        self.errdir = opts.errdir
        self.iomap = make_iomap()

        self.taskcount = 0
        self.tasks = []
        self.running = []
        self.done = []

        self.askpass_socket = None

    def run(self):
        """Processes tasks previously added with add_task."""
        try:
            if self.outdir or self.errdir:
                writer = Writer(self.outdir, self.errdir)
                writer.start()
            else:
                writer = None

            if self.askpass:
                pass_server = PasswordServer()
                pass_server.start(self.iomap, self.limit)
                self.askpass_socket = pass_server.address

            self.set_sigchld_handler()

            try:
                self.update_tasks(writer)
                wait = None
                while self.running or self.tasks:
                    # Opt for efficiency over subsecond timeout accuracy.
                    if wait is None or wait < 1:
                        wait = 1
                    self.iomap.poll(wait)
                    self.update_tasks(writer)
                    wait = self.check_timeout()
            except KeyboardInterrupt:
                # This exception handler tries to clean things up and prints
                # out a nice status message for each interrupted host.
                self.interrupted()

        except KeyboardInterrupt:
            # This exception handler doesn't print out any fancy status
            # information--it just stops.
            pass

        if writer:
            writer.signal_quit()
            writer.join()

        statuses = [task.exitstatus for task in self.done]
        return statuses

    def clear_sigchld_handler(self):
        signal.signal(signal.SIGCHLD, signal.SIG_DFL)

    def set_sigchld_handler(self):
        # TODO: find out whether set_wakeup_fd still works if the default
        # signal handler is used (I'm pretty sure it doesn't work if the
        # signal is ignored).
        signal.signal(signal.SIGCHLD, self.handle_sigchld)
        # This should keep reads and writes from getting EINTR.
        if hasattr(signal, 'siginterrupt'):
            signal.siginterrupt(signal.SIGCHLD, False)

    def handle_sigchld(self, number, frame):
        """Apparently we need a sigchld handler to make set_wakeup_fd work."""
        # Write to the signal pipe (only for Python <2.5, where the
        # set_wakeup_fd method doesn't exist).
        if self.iomap.wakeup_writefd:
            os.write(self.iomap.wakeup_writefd, '\0')
        for task in self.running:
            if task.proc:
                task.proc.poll()
        # Apparently some UNIX systems automatically reset the SIGCHLD
        # handler to SIG_DFL.  Reset it just in case.
        self.set_sigchld_handler()

    def add_task(self, task):
        """Adds a Task to be processed with run()."""
        self.tasks.append(task)

    def update_tasks(self, writer):
        """Reaps tasks and starts as many new ones as allowed."""
        # Mask signals to work around a Python bug:
        #   http://bugs.python.org/issue1068268
        # Since sigprocmask isn't in the stdlib, clear the SIGCHLD handler.
        # Since signals are masked, reap_tasks needs to be called once for
        # each loop.
        keep_running = True
        while keep_running:
            self.clear_sigchld_handler()
            self._start_tasks_once(writer)
            self.set_sigchld_handler()
            keep_running = self.reap_tasks()

    def _start_tasks_once(self, writer):
        """Starts tasks once.

        Due to http://bugs.python.org/issue1068268, signals must be masked
        when this method is called.
        """
        while 0 < len(self.tasks) and len(self.running) < self.limit:
            task = self.tasks.pop(0)
            self.running.append(task)
            task.start(self.taskcount, self.iomap, writer, self.askpass_socket)
            self.taskcount += 1

    def reap_tasks(self):
        """Checks to see if any tasks have terminated.

        After cleaning up, returns the number of tasks that finished.
        """
        still_running = []
        finished_count = 0
        for task in self.running:
            if task.running():
                still_running.append(task)
            else:
                self.finished(task)
                finished_count += 1
        self.running = still_running
        return finished_count

    def check_timeout(self):
        """Kills timed-out processes and returns the lowest time left."""
        if self.timeout <= 0:
            return None

        min_timeleft = None
        for task in self.running:
            timeleft = self.timeout - task.elapsed()
            if timeleft <= 0:
                task.timedout()
                continue
            if min_timeleft is None or timeleft < min_timeleft:
                min_timeleft = timeleft

        if min_timeleft is None:
            return 0
        else:
            return max(0, min_timeleft)

    def interrupted(self):
        """Cleans up after a keyboard interrupt."""
        for task in self.running:
            task.interrupted()
            self.finished(task)

        for task in self.tasks:
            task.cancel()
            self.finished(task)

    def finished(self, task):
        """Marks a task as complete and reports its status to stdout."""
        self.done.append(task)
        n = len(self.done)
        task.report(n)

class IOMap(object):
    """A manager for file descriptors and their associated handlers.

    The poll method dispatches events to the appropriate handlers.
    """
    def __init__(self):
        self.readmap = {}
        self.writemap = {}

        # Setup the wakeup file descriptor to avoid hanging on lost signals.
        wakeup_readfd, wakeup_writefd = os.pipe()
        self.register_read(wakeup_readfd, self.wakeup_handler)
        # TODO: remove test when we stop supporting Python <2.5
        if hasattr(signal, 'set_wakeup_fd'):
            signal.set_wakeup_fd(wakeup_writefd)
            self.wakeup_writefd = None
        else:
            self.wakeup_writefd = wakeup_writefd

    def register_read(self, fd, handler):
        """Registers an IO handler for a file descriptor for reading."""
        self.readmap[fd] = handler

    def register_write(self, fd, handler):
        """Registers an IO handler for a file descriptor for writing."""
        self.writemap[fd] = handler

    def unregister(self, fd):
        """Unregisters the given file descriptor."""
        if fd in self.readmap:
            del self.readmap[fd]
        if fd in self.writemap:
            del self.writemap[fd]

    def poll(self, timeout=None):
        """Performs a poll and dispatches the resulting events."""
        if not self.readmap and not self.writemap:
            return
        rlist = list(self.readmap)
        wlist = list(self.writemap)
        try:
            rlist, wlist, _ = select.select(rlist, wlist, [], timeout)
        except select.error:
            _, e, _ = sys.exc_info()
            errno = e.args[0]
            if errno == EINTR:
                return
            else:
                raise
        for fd in rlist:
            handler = self.readmap[fd]
            handler(fd, self)
        for fd in wlist:
            handler = self.writemap[fd]
            handler(fd, self)

    def wakeup_handler(self, fd, iomap):
        """Handles read events on the signal wakeup pipe.

        This ensures that SIGCHLD signals aren't lost.
        """
        try:
            os.read(fd, READ_SIZE)
        except (OSError, IOError):
            _, e, _ = sys.exc_info()
            errno, message = e.args
            if errno != EINTR:
                sys.stderr.write('Fatal error reading from wakeup pipe: %s\n'
                        % message)
                raise FatalError

class PollIOMap(IOMap):
    """A manager for file descriptors and their associated handlers.

    The poll method dispatches events to the appropriate handlers.
    Note that `select.poll` is not available on all operating systems.
    """
    def __init__(self):
        self._poller = select.poll()
        super(PollIOMap, self).__init__()

    def register_read(self, fd, handler):
        """Registers an IO handler for a file descriptor for reading."""
        super(PollIOMap, self).register_read(fd, handler)
        self._poller.register(fd, select.POLLIN)

    def register_write(self, fd, handler):
        """Registers an IO handler for a file descriptor for writing."""
        super(PollIOMap, self).register_write(fd, handler)
        self._poller.register(fd, select.POLLOUT)

    def unregister(self, fd):
        """Unregisters the given file descriptor."""
        super(PollIOMap, self).unregister(fd)
        self._poller.unregister(fd)

    def poll(self, timeout=None):
        """Performs a poll and dispatches the resulting events."""
        if not self.readmap and not self.writemap:
            return
        try:
            event_list = self._poller.poll(timeout)
        except select.error:
            _, e, _ = sys.exc_info()
            errno = e.args[0]
            if errno == EINTR:
                return
            else:
                raise
        for fd, event in event_list:
            if event & (select.POLLIN | select.POLLHUP):
                handler = self.readmap[fd]
                handler(fd, self)
            if event & (select.POLLOUT | select.POLLERR):
                handler = self.writemap[fd]
                handler(fd, self)

def make_iomap():
    """Return a new IOMap or PollIOMap as appropriate.

    Since `select.poll` is not implemented on all platforms, this ensures that
    the most appropriate implementation is used.
    """
    if hasattr(select, 'poll'):
        return PollIOMap()
    else:
        return IOMap()

class Writer(threading.Thread):
    """Thread that writes to files by processing requests from a Queue.

    Until AIO becomes widely available, it is impossible to make a nonblocking
    write to an ordinary file.  The Writer thread processes all writing to
    ordinary files so that the main thread can work without blocking.
    """
    OPEN = object()
    EOF = object()
    ABORT = object()

    def __init__(self, outdir, errdir):
        threading.Thread.__init__(self)
        # A daemon thread automatically dies if the program is terminated.
        self.setDaemon(True)
        self.queue = queue.Queue()
        self.outdir = outdir
        self.errdir = errdir

        self.host_counts = {}
        self.files = {}

    def run(self):
        while True:
            filename, data = self.queue.get()
            if filename == self.ABORT:
                return

            if data == self.OPEN:
                self.files[filename] = open(filename, 'wb', buffering=1)
                psshutil.set_cloexec(self.files[filename])
            else:
                dest = self.files[filename]
                if data == self.EOF:
                    dest.close()
                else:
                    dest.write(data)
                    dest.flush()

    def open_files(self, host):
        """Called from another thread to create files for stdout and stderr.

        Returns a pair of filenames (outfile, errfile).  These filenames are
        used as handles for future operations.  Either or both may be None if
        outdir or errdir or not set.
        """
        outfile = errfile = None
        if self.outdir or self.errdir:
            count = self.host_counts.get(host, 0)
            self.host_counts[host] = count + 1
            if count:
                filename = "%s.%s" % (host, count)
            else:
                filename = host
            if self.outdir:
                outfile = os.path.join(self.outdir, filename)
                self.queue.put((outfile, self.OPEN))
            if self.errdir:
                errfile = os.path.join(self.errdir, filename)
                self.queue.put((errfile, self.OPEN))
        return outfile, errfile

    def write(self, filename, data):
        """Called from another thread to enqueue a write."""
        self.queue.put((filename, data))

    def close(self, filename):
        """Called from another thread to close the given file."""
        self.queue.put((filename, self.EOF))

    def signal_quit(self):
        """Called from another thread to request the Writer to quit."""
        self.queue.put((self.ABORT, None))

<|endoftext|>