Esempio n. 1
0
def CKYparse(words, grammar):
	table = [["-" for x in range(len(words))] for x in range(len(words))] 
	header = []
	for word in words:
		tmp = word[:word.rfind("/")]
		tmp = unicode(tmp, 'utf-8')
		header.append(tmp)
	count = 0
	for j in range(len(words)):
		word = unicode(words[j], 'utf-8')
		tag = word[word.rfind("/")+1:]
		word = word[:word.rfind("/")]
		table[j][j] = tag
		for i in range(j):
			i = abs(i-j)-1
			print "i: [%s][%s]" %(i, j)
			T1 = table[i][j-1]
			print "T1: %s" %T1
			T2 = table[i+1][j]
			print "T2: %s" %T2
			count += 1
			table[i][j] = count
		print " ----------------------- "


	print tabulate(table, headers=header)
Esempio n. 2
0
def configPlot(scale=1e4, verbose=False):

    prefix = '/data/user/fmcnally/anisotropy/maps/merged/'
    fileList = np.array(glob.glob(prefix + 'IC?*_24H_sid.fits'))
    alpha = 1/20.
    deg = 180./np.pi

    # Sort fileList according to configs
    configs = np.array([os.path.basename(f).split('_')[0] for f in fileList])
    csort = configs.argsort()
    configs, fileList = configs[csort], fileList[csort]

    dipoleParams = np.zeros((len(fileList), 6))
    for i, f in enumerate(fileList):

        data = mapFunctions.getMap(f, mapName='data')
        bg = mapFunctions.getMap(f, mapName='bg')
        p = mapFunctions.multifit(1, data, bg, alpha, params=True)
        if verbose:
            print configs[i]
            ptable = [[key, p[key], p['d'+key]] for key in sorted(p.keys())]
            print tabulate(ptable, headers=['Ylm','Value','Error'])
        dipoleParams[i] = getDipole(p)

    p0, dp0, theta, dTheta, phi, dPhi = dipoleParams.T
    if verbose:
        for i, config in enumerate(configs):
            print config, ':'
            print 'Theta: %.3f +/- %.3f' % (theta[i]*deg, dTheta[i]*deg)
            print 'Phi: %.3f +/- %.3f' % (phi[i]*deg, dPhi[i]*deg)

    fig = plt.figure(figsize=(17,6))
    x = range(len(configs))
    pltParams = {'fmt':'.','lw':2,'ms':14}

    ax = fig.add_subplot(121)
    ax.set_title('Dipole Strength vs Energy')
    ax.set_xlabel(r'log$_{10}$(E/GeV)')
    ax.set_ylabel('Dipole Strength (x %s)' % scale)
    ax.errorbar(x, p0*scale, yerr=dp0*scale, **pltParams)
    ax.set_xlim(-1, x[-1]+1)
    ax.set_xticks(x)
    ax.set_xticklabels(configs)

    ax = fig.add_subplot(122)
    ax.set_title('Dipole Phase vs Energy')
    ax.set_xlabel(r'log$_{10}$(E/GeV)')
    ax.set_ylabel(r'Dipole Phase ($\phi^{\circ}$)')

    phi, dPhi = phi*deg, dPhi*deg
    phi[phi>180] -= 360
    ax.errorbar(x, phi, yerr=dPhi, **pltParams)

    ax.set_xlim(-1, x[-1]+1)
    ax.set_xticks(x)
    ax.set_xticklabels(configs)

    plt.show()
def write_report(test_name, assert_error, col1, col2):
    if assert_error:
        print(test_name + "Test failed for one or more instances")
        report = build_table(col1, col2)
        headers = ["expected", "actual"]
        print(tabulate(report, headers, tablefmt='grid'))
    else:
        print(test_name + "Test completed successfully")
        report = build_table(col1, col2)
        headers = ["expected", "actual url or status"]
        print(tabulate(report, headers, tablefmt='grid'))
    return
def CrossCorrelation(X):

	n = X.shape[1]
	comb = combinations(range(n),2)
	table = []

	for i,j in comb:
		current_cor = ComputeCorrelationCoefficient(X[:,i],X[:,j])
		row = [features[i],features[j],current_cor]
		table.append(row)

	headers = ["Feautre 1","Feature 2","Correlation Coefficient"]
	print "Cross Correlation Coefficient Table"
	print tabulate(table,headers,tablefmt = "fancy_grid")
def ShapiroWilkTest(X):

	n = X.shape[1]
	table = []
	for i in xrange(n):
		try:
			results = shapiro(X[:,i][:4000])	
		except:
			pass
		row = [features[i],results[0],results[1]]
		table.append(row)
	headers = ["Features","W","p-value"]
	print "Shapiro-wilk test"
	print tabulate(table,headers,tablefmt = "fancy_grid")
def get_reachable_dev():

    api_url = "https://devnetsbx-netacad-apicem-3.cisco.com/api/v1/reachability-info"

    ticket = get_ticket()

    headers = {"content-type": "application/json", "x-Auth-Token": ticket}

    resp = requests.get(api_url, headers=headers, verify=False)

    print("Status of Host request:", resp.status_code)

    response_json = resp.json()

    #pprint(response_json)

    host_list = []
    i = 0

    for item in response_json["response"]:
        i += 1
        host = [i, item["discoveryId"], item["mgmtIp"]]
        host_list.append(host)

    table_header = ["Number", "Type", "IP"]

    print(tabulate(host_list, table_header))
Esempio n. 7
0
def print_devices():
    # NETWORK-DEVICE API URL
    #api_url = "https://{YOUR-APICEM}.cisco.com/api/v1/network-device"
    api_url = "https://devnetsbx-netacad-apicem-1.cisco.com/api/v1/network-device"

    # Setup API request headers.
    ticket = get_ticket()
    headers = {"content-type": "application/json", "X-Auth-Token": ticket}

    resp = requests.get(api_url, headers=headers, verify=False)
    print("Status of GET /network-device request: ",
          resp.status_code)  # This is the http request status
    # Check if the request status was 200/OK
    if resp.status_code != 200:
        raise Exception("Status code does not equal 200. Response text: " +
                        resp.text)
    # Get the json-encoded content from response
    response_json = resp.json()

    # Now create a list of host summary info
    device_list = []
    i = 0
    for item in response_json["response"]:
        i += 1
        device = [i, item["type"], item["managementIpAddress"]]
        device_list.append(device)

    table_header = ["Number", "Type", "IP"]
    print(tabulate(device_list, table_header))
def print_host():
    api_url = "https://sandboxapicem.cisco.com/api/v1/host"
    ticket = get_ticket()
    headers = {
    "content-type": "application/json",
    "X-Auth-Token": ticket
    }
    # Request and handle errors.
    resp = requests.get(api_url, headers=headers, verify=False)
    response_json = resp.json()
    # Parse and format the JSON response data
    # Create a new list
    host_list = []
    # Generate the for loop to create a list
    i = 0
    for item in response_json["response"]:
        i+=1
        host = [
                i,
                item["hostType"],
                item["hostIp"] 
                ]
        host_list.append( host )
    table_header = ["Number", "Type", "IP"]
    print( tabulate(host_list, table_header) )
Esempio n. 9
0
    def print_lp(self):
        lp = [["" for j in range(0, self.n + 3)] for i in range(0, self.m + 2)]

        lp[0][0] = "Maximize"
        lp[1][0] = "Such that"

        for i in range(1, self.m + 1):
            for j in range(1, self.n + 1):
                if j == 1:
                    x = ""
                else:
                    x = "+"

                lp[i][j] = x + str(self.a[i - 1, j - 1]) + "x_" + str(j)

        for j in range(1, self.n + 1):
            if j == 1:
                x = ""
            else:
                x = "+"

            lp[0][j] = x + str(self.c[j - 1]) + "x_" + str(j)

        for i in range(1, self.m + 1):
            lp[i][-1] = "<= " + str(self.b[i - 1])

        print(tabulate(lp))
Esempio n. 10
0
def get_interface_list_table(sshCli):

    ip_addr_interfaces = []
    output = sshCli.send_command("show ip int brief")
    lista = output.split()

    for i in range(7, len(lista), 6):
        ip_addr_interfaces.append(lista[i])

    m = manager.connect(host="192.168.56.102",
                        port=830,
                        username="******",
                        password="******",
                        hostkey_verify=False)
    netconf_filter = """
    <filter>
        <interfaces-state xmlns="urn:ietf:params:xml:ns:yang:ietf-interfaces"/>
    </filter>
    """
    netconf_reply = m.get(filter=netconf_filter)

    netconf_reply_dict = xmltodict.parse(netconf_reply.xml)
    tabla = []
    i = 0
    for interface in netconf_reply_dict["rpc-reply"]["data"][
            "interfaces-state"]["interface"]:
        tabla.append([
            interface["name"], ip_addr_interfaces[i], interface["phys-address"]
        ])
        i += 1
    print()
    print(tabulate(tabla, headers=["Nombre Interfaz", "IP", "MAC"]))
Esempio n. 11
0
def routing_table():

    requests.packages.urllib3.disable_warnings()
    url = "https://192.168.56.101/restconf/data/ietf-routing:routing-state"

    headers = {
        "Accept": "application/yang-data+json",
        "Content-Type": "application/yang-data+json"
    }
    basic_auth = ("cisco", "cisco123!")

    resp = requests.get(url, auth=basic_auth, headers=headers, verify=False)
    resp_json = resp.json()

    routes = []
    counter = 0
    for item in resp_json['ietf-routing:routing-state']['routing-instance'][0][
            'ribs']['rib'][0]['routes']['route']:
        counter += 1
        route = [
            counter, item['destination-prefix'],
            item['next-hop']['outgoing-interface']
        ]
        routes.append(route)

    tableHeader = ["ID", "Destination network", "Outgoing interface"]
    print(tabulate(routes, tableHeader))
Esempio n. 12
0
def get_Network_Devices(url, ticket):
    get_Network_Devices_url = url + "network-device"
    headers = {
        "Content-type": "application/json",
        "X-Auth-Token": ticket,
    }
    resp = requests.get(get_Network_Devices_url, headers=headers, verify=False)
    if resp.status_code == 200:
        resp_json = resp.json()
        Lista_equipos = []
        i = 0
        for equipo in resp_json["response"]:
            i += 1
            Disp = [
                i,
                #equipo["family"],
                equipo["series"],
                equipo["hostname"],
                equipo["managementIpAddress"],
                equipo["macAddress"],
                equipo["softwareVersion"]
            ]
            Lista_equipos.append(Disp)
            table_header = [
                "Indice", "Modelo", "Hostname", "IP Gestion", "MAC",
                "Version SW"
            ]
        print("\n", tabulate(Lista_equipos, table_header))
    else:
        print("EL CODIGO DE ERROR ES: ", resp.status_code)
Esempio n. 13
0
def do_version(_):
    from tabulate import tabulate
    import importlib_metadata

    from janis_assistant.__meta__ import __version__ as jr_version
    from janis_core.__meta__ import __version__ as jc_version
    import janis_core.toolbox.entrypoints as EP

    fields = [["janis-core", jc_version], ["janis-assistant", jr_version]]
    # eps = pkg_resources.iter_entry_points(group=EP.EXTENSIONS)
    eps = importlib_metadata.entry_points().get(EP.EXTENSIONS, [])
    skip_eps = {"assistant"}
    for entrypoint in eps:
        if entrypoint.name in skip_eps:
            continue
        try:
            version = entrypoint.load().__version__
            if version:
                fields.append(["janis-" + entrypoint.name, version])
            skip_eps.add(entrypoint.name)

        except Exception as e:
            Logger.log_ex(e)

    print(tabulate(fields))
Esempio n. 14
0
def get_ippool():

    api_url = "https://devnetsbx-netacad-apicem-3.cisco.com/api/v1/ippool"

    ticket = get_ticket()

    headers = {"content-type": "application/json", "x-Auth-Token": ticket}

    resp = requests.get(api_url, headers=headers, verify=False)

    print("Status of Host request:", resp.status_code)

    response_json = resp.json()

    host_list = []
    i = 0

    for item in response_json["response"]:
        i += 1
        host = [i, item["ipPool"]]
        host_list.append(host)

    table_header = ["Number", "ipPool"]

    print(tabulate(host_list, table_header))
Esempio n. 15
0
def Get_Host(ticket):
    try:
        Url = "https://devnetsbx-netacad-apicem-3.cisco.com/api/v1/host"
        headers = {"Content-Type": "application/json", "X-Auth-Token": ticket}

        respuesta = requests.get(Url, headers=headers, verify=False)
        outFormat = respuesta.json()

        resq = outFormat["response"]
        Host_list = []
        Host = []
        Encabezado = [
            "Numero", "IP", "MAC", "Tipo", "Conectado a ID", "Conectado a IP",
            "Conectado a MAC", "Conectado a Nombre", "VLAN_ID", "Ult.Update",
            "Origen", "Punto Presencia", "Punto Apego", "Sub Tipo", "ID"
        ]

        for e in resq:
            Host.append(e.values())
        for v in Host:
            Host_list.append(v)

        return print("\nEstos son los Host Disponibles: \n\n",
                     tabulate(Host_list, Encabezado, showindex=True))
    except:
        return print(
            "\nNo es posible obtener informacion del servidor Cod.Error: ",
            respuesta.status_code,
            "\nPara mas informacion visitar: https://developer.mozilla.org/es/docs/Web/HTTP/Status"
        )
Esempio n. 16
0
 def get_table(self):
     from tabulate import tabulate
     if len(self)==0:
         return repr(self) + '\n' + '<Empty>'
     else:
         rows = self[0].get_table_headers() + [pair.get_table_row() for pair in self]
         return repr(self)+'\n  '+tabulate(rows).replace('\n', '\n  ')
Esempio n. 17
0
    def __str__(self):
        outs = str()
        for b in self._files._files:
            outs += str(b)
            count = check_comments(b._filename)
            outs +="\n\n    Lines: "+str(count._linecount)
            outs +="\n    Comments: "+str(count._commentcount)
            outs +="\n    Functions: "+str(count._functioncount)
            t = tabulate(b.getResults(), linecount=count._linecount, commentcount=count._commentcount, functioncount=count._functioncount, correctweight= int(self.ui.correctweight.text()), wrongweight = int(self.ui.incorrectweight.text()), errorweight = int(self.ui.errorweight.text()), commentfreq= int(self.ui.comment_freq.text()), functionfreq= int(self.ui.avg_func_len.text()), includeComments= self.ui.commentcheck.checkState(), includeFunctions= self.ui.functioncheck.checkState())
            outs+= "\n    Correct: "+str(t._correctraw)
            outs+= "\n    Errors: "+str(t._errorraw)
            outs+= "\n    Incorrect: "+str(t._incorrectraw)

            outs+= "\n    Total Score: "+str(t.getScore())
            outs +="\n    IO Score: " +str(t.getIOScore())
            outs += "\n    Comment Score: "
            if (self.ui.commentcheck.checkState()):
                outs+= str(t.getCommentScore())
            else:
              outs+= "N/A"
            outs+= "\n    Function Score: "
            if (self.ui.functioncheck.checkState()):
                outs+= str(t.getFunctionScore())
            else:
                outs+= "N/A"
            outs+= "\n\n"
        return outs
def print_netDevices():
    api_url = "https://SandBoxAPICEM.cisco.com/api/v1/network-device"
    ticket = get_ticket()
    headers = {
        "content-type": "application/json",
        "X-Auth-Token": ticket
    }
    resp = requests.get(api_url, headers=headers, verify=False)
    print("Status of GET /device request: ", resp.status_code)
    if resp.status_code != 200:
        raise Exception("Status code does not equal 200. Response text: " + resp.text)
    response_json = resp.json()

    device_list = []
    i = 0
    for item in response_json["response"]:
        i += 1
        device = [
                    i, 
                    item["type"], 
                    item["managementIpAddress"] 
        ]
    device_list.append( device )
    table_header = [
                "Number", 
                "Type", 
                "IP"
               ]
    print( tabulate(device_list, table_header) )
Esempio n. 19
0
def get_routes():
    netconf_filter = """
    <filter>
        <routing-state xmlns="urn:ietf:params:xml:ns:yang:ietf-routing"/>
    </filter>
    """
    try:
        m=manager.connect(
            host=var_hostIP,
            port=830,
            username=var_user,
            password=var_password,
            hostkey_verify=False
            )    
    except:
        print("\nERROR !!! CON LOS DATOS INTRODUCIDOS NO SE HA PODIDO CONECTAR CON EL EQUIPO")
        return  
    routes_replay = m.get(filter=netconf_filter)
    routes_reply_dict = xmltodict.parse(routes_replay.xml)
    route_list=[]
    i = 0
    for key in routes_reply_dict["rpc-reply"]["data"]["routing-state"]["routing-instance"]["ribs"]["rib"]["routes"]["route"]:
        i+=1
        route=[
            i,
            key["destination-prefix"],
            key["next-hop"]["outgoing-interface"],key["source-protocol"]]
        route_list.append(route)
        table_header = ["Indice","Prefijo","Interface Next-Hop","Protocolo"]
    print("\n",tabulate(route_list, table_header))
Esempio n. 20
0
def get_Interfaces(url, ticket):
    get_Interface_url = url + "interface"
    headers = {
        "Content-type": "application/json",
        "X-Auth-Token": ticket,
    }
    resp = requests.get(get_Interface_url, headers=headers, verify=False)
    if resp.status_code == 200:
        resp_json = resp.json()
        Lista_items = []
        i = 1
        device_id = None
        for item in resp_json["response"]:
            if device_id != item["deviceId"]:
                device_id = item["deviceId"]
                i += 1
                Disp = [
                    i, item["series"], item["pid"], item["portName"],
                    item["ipv4Address"], item["ipv4Mask"]
                ]
            else:
                Disp = [
                    "", "", "", item["portName"], item["ipv4Address"],
                    item["ipv4Mask"]
                ]
            Lista_items.append(Disp)
            table_header = [
                "Indice", "Familia", "Equipo", "Interface", "Direccion IP",
                "Mascara"
            ]
        print("\n", tabulate(Lista_items, table_header))
    else:
        print("EL CODIGO DE ERROR ES: ", resp.status_code)
Esempio n. 21
0
def Get_NameSpace(Ticket):
    try:
        while True:
            Url = "https://devnetsbx-netacad-apicem-3.cisco.com/api/v1/file/namespace"

            headers = {
                "Content-Type": "application/json",
                "X-Auth-Token": Ticket
            }

            respuesta = requests.get(Url, headers=headers, verify=False)
            outFormat = respuesta.json()

            list_Naspa = []
            l = []
            Encabezado = ["Nombre De Espacios Disponibles"]
            #Encabezado2=["Direccion","Direccion Geografica","Nombre","ID"]

            dic = outFormat["response"]

            for v in dic:
                l = [v]
                list_Naspa.append(l)

            return print(
                "\nEstos son los nombres de espacios disposnibles: \n\n",
                tabulate(list_Naspa, Encabezado))
    except:
        return print(
            "\nNo es posible obtener informacion del servidor Cod.Error: ",
            respuesta.status_code,
            "\nPara mas informacion visitar: https://developer.mozilla.org/es/docs/Web/HTTP/Status"
        )
Esempio n. 22
0
def Get_Device_Network(ticket):
    try:
        Url = "https://devnetsbx-netacad-apicem-3.cisco.com/api/v1/network-device"
        headers = {"Content-Type": "application/json", "X-Auth-Token": ticket}

        respuesta = requests.get(Url, headers=headers, verify=False)
        outFormat = respuesta.json()

        Device_list = []
        Encabezado = [
            "Number", "Family", "  SerialNumber  ", "  Type  ", "MAC", "IP",
            "CountInterface"
        ]
        c = 0

        for key in outFormat['response']:
            network = [
                c, key['family'], key['serialNumber'], key['type'],
                key['macAddress'], key['managementIpAddress'],
                key['interfaceCount']
            ]
            c += 1
            Device_list.append(network)
        return print("\nEstos son los dispositivos de red disponibles: \n\n",
                     tabulate(Device_list, Encabezado))
    except:
        return print(
            "\nNo es posible obtener informacion del servidor Cod.Error: ",
            respuesta.status_code,
            "\nPara mas informacion visitar: https://developer.mozilla.org/es/docs/Web/HTTP/Status"
        )
Esempio n. 23
0
 def get_table(self):
     from tabulate import tabulate
     if len(self)==0:
         return repr(self) + '\n' + '<Empty>'
     else:
         rows = self[0].get_table_headers() + [pair.get_table_row() for pair in self]
         return repr(self)+'\n  '+tabulate(rows).replace('\n', '\n  ')
Esempio n. 24
0
def VerTrabajos2(usuario, conn):
    cur = conn.cursor()
    ImprimirTitulo("Ver Trabajos")
    cur.execute(empresasQueOfrecenTrabajos)
    trabajosDisponibles = cur.fetchall()
    cantidad_ofertas = len(trabajosDisponibles)
    Imprimir(tabulate(trabajosDisponibles, headers=["Id empresa", "Nombre empresa", "Trabajos ofrecidos"],showindex=range(1,cantidad_ofertas+1)))
    Imprimir("{} Volver\n{} Salir".format(cantidad_ofertas+1, cantidad_ofertas+2))
    seleccion = ValidarOpcion(range(1, cantidad_ofertas+3))
    if seleccion == cantidad_ofertas+1:
        return
    elif seleccion == cantidad_ofertas+2:
        cur.close()
        conn.close()
        sys.exit()
    else:
        idTrabajoSeleccionado = trabajosDisponibles[seleccion-1][0]
        opciones = ["Ver empresa",
                    "Volver",
                    "Salir"]
        ImprimirOpciones(opciones)
        seleccion = ValidarOpcion(range(1,4))
        if seleccion == 1:
            VerEmpresa(idTrabajoSeleccionado, usuario, conn)
        elif seleccion == 2:
            cur.close()
            VerTrabajos2(idTrabajoSeleccionado, conn)
        elif seleccion == 3:
            cur.close()
            conn.close()
            sys.exit()
    return
def print_hosts():
    api_url = "https://sandboxapicem.cisco.com/api/v1/host"
    ticket = get_ticket()

    headers = {
    "content-type": "application/json",
    "X-Auth-Token": ticket
    }

    resp = requests.get(api_url, headers=headers, verify=False)

    print("Status of /host request: ", resp.status_code)

    if resp.status_code != 200:
        raise Exception("Status code does not equal 200. Response text: " + resp.text)

    response_json = resp.json()

    host_list = []
    i = 0

    for item in response_json["response"]:
        i+=1
        host = [
        i,
        item["hostType"],
        item["hostIp"]
        ]
        host_list.append( host )
        table_header = ["Number", "Type", "IP"]
        print( tabulate(host_list, table_header) )
Esempio n. 26
0
    def getTablaLREnCadena(self):
        tablaAux = [['' for _ in range(len(self._tablaLR[0]))]
                    for _ in range(len(self._tablaLR))]

        # Se copia la primer fila y la primer columna
        for i in range((len(self._tablaLR[0])
                        if len(self._tablaLR[0]) > len(self._tablaLR) else len(
                            self._tablaLR))):
            if i < len(self._tablaLR[0]):
                tablaAux[0][i] = self._tablaLR[0][i]
            if i < len(self._tablaLR):
                tablaAux[i][0] = self._tablaLR[i][0]

        for i in range(1, len(self._tablaLR)):
            for j in range(1, len(self._tablaLR[0])):
                elemento = self._tablaLR[i][j]

                if elemento != '':
                    if type(elemento) == int:
                        # Se trata de el número de regla de una reducción
                        tablaAux[i][j] = 'r{}'.format(
                            elemento) if elemento != 0 else 'Aceptar'
                    elif type(elemento) == EstadoItems:
                        # Se trata de un desplazamiento
                        if self._gramatica.isSimboloTerminal(
                                self._tablaLR[0][j]):
                            tablaAux[i][j] = 'd{}'.format(elemento.getNombre())
                        else:
                            tablaAux[i][j] = elemento.getNombre()

        return tabulate(tablaAux, headers="firstrow")
Esempio n. 27
0
def print_hosts():

    #datos para establecer la conexión
    ticket = get_ticket()
    api_url = "https://sandboxapicem.cisco.com/api/v1/host"
    headers = {"content-type": "application/json", "X-Auth-Token": ticket}

    body_json = {"username": "******", "password": "******"}

    # petición
    resp = requests.get(api_url, headers=headers, verify=None)
    #comprobacion
    print("Status Code: ", resp.status_code)
    if resp.status_code != 200:
        raise Exception("Status code not equal 200. Response text: ",
                        resp.text)
    #convertir la respuesta a json
    response_json = resp.json()

    host_list = []
    i = 0
    for item in response_json["response"]:
        i += 1
        host = [i, item["hostType"], item["hostIp"], item["hostMac"]]
        host_list.append(host)

    table_header = ["Number", "Type", "IP", "MAC"]
    print(tabulate(host_list, table_header))
Esempio n. 28
0
def selectFunc():
    global operation
    operation = input('''
Please First Select the function number 1 to get access to the other functions deploy:
1 for getTicket
2 for getHosts
3 for getNetworkDevices
4 for getRoute
After select your operation press Enter
''')

    if operation == '1':
        getTicket()
        print("Esto es un string secundario:", ticket)

    if operation == '2':
        getHosts()
        tableHeader = ["Number", "Type", "IP", "MAC"]
        print(tabulate(hostList, tableHeader))

    if operation == '3':
        getNetworkDevices()
        for equipo in response_json['response']:
            print("El hostname", equipo['hostname'], "pertenece a la familia",
                  equipo['family'], "su MAC es", equipo['macAddress'],
                  "y su version de IOS es:", equipo['softwareVersion'])

    again()
Esempio n. 29
0
def print_host():
    url = "https://devnetsbx-netacad-apicem-3.cisco.com/api/v1/host"
    ticket = get_ticket()
    headers = {

    'Content-Type': 'application/json',
    'X-Auth-Token': ticket
    }
    resp = requests.get(url, headers=headers, verify=False)
    response_json = resp.json()
    HostList = []
    counter = 0

    for item in response_json["response"]:
        counter += 1
        host = [
            counter,
            item["hostType"],
            item["hostIp"],
            item["hostMac"]
            ]
        HostList.append(host)

    tableHeader = ["Number","Name","IP","MAC"]
    print("HOSTS:")
    print(tabulate(HostList,tableHeader))
Esempio n. 30
0
def print_hosts():
    api_url = "https://devnetsbx-netacad-apicem-1.cisco.com/api/v1/host"
    ticket = get_ticket()
    headers = {"content-type": "application/json", "X-Auth-Token": ticket}

    resp = requests.get(api_url, headers=headers, verify=False)
    # This is the http request status
    print("Status of /host request: ", resp.status_code)
    # Check if the request status was 200/OK
    if resp.status_code != 200:
        raise Exception("Status code does not equal 200. Response text: " +
                        resp.text)
    # Get the json-encoded content from response
    response_json = resp.json()

    # Now create a list of host info to be held in host_list
    host_list = []
    i = 0
    for item in response_json["response"]:
        i += 1
        host = [i, item["hostType"], item["hostIp"]]
        host_list.append(host)

    table_header = ["Number", "Type", "IP"]
    print(tabulate(host_list, table_header))
def MostrarElementosIndicados(respHosts, elem):

    tableHeader = ["Elemento"]
    for i in range(len(elem)):
        tableHeader.append(elem[i])

    print(
        "                             *************     LISTADO DE LOCALIZACIONES  **************"
    )
    print(
        "                             ***********************************************************"
    )
    print("\n ")

    hostListFinal = []
    hostList = []
    counter = 0
    for resp in respHosts['response']:
        counter += 1
        hostList = [counter]
        for lisElem in elem:
            if lisElem in resp:
                new = resp[lisElem]
            else:
                new = ""
            hostList.append(new)
        hostListFinal.append(hostList)

    print(tabulate(hostListFinal, tableHeader))
    input("\nPulsa Enter para continuar....")
    return
def parsing_json():
    if JSON_KEYS is None:
        print("-" * 120)
        print(
            "JSON_KEYS is missing. Ensure you use format defined bellow, you can add/remove keys, but keep exact the same format."
        )
        print(
            "As I'm not exactly checking format of input, ensure you will follow example.\n\nExample to define JSON_KEYS:\n\n"
        )
        print(
            "export JSON_KEYS=\"'deviceId', 'site-id', 'host-name', 'local-system-ip'\""
        )
        print(
            "If you need help to identify JSON_KEYS look to JSON_OUTPUT.txt file in your directory."
        )
        print("-" * 120)
        exit("1")

    (get_api_json, is_jason_status) = get_api_only()
    #print("-" * 120)

    if is_jason_status == False:
        print(
            "Output from API is not JSON, parsing function is only for JSON outputs...."
        )
        print("Exiting...")
        exit(0)
    else:
        json_parameters = ast.literal_eval(JSON_KEYS)
        print("-" * 120)
        print(
            "Parsing api call defined by API_CALLs based on keys provided in JSON_KEYS:"
        )
        print(json_parameters)
        print("-" * 120)
        data = get_api_json
        devices = []
        devices = [{key: device.get(key, "N/A")
                    for key in json_parameters} for device in data["data"]]
        df = pandas.DataFrame(devices)
        headers = json_parameters
        print(tabulate(df, headers, tablefmt="fancy_grid"))
        yes_or_no_output = yes_or_no("Would you like to save output to csv? ")
        if yes_or_no_output == True:
            try:
                filename = input(
                    "Enter Filename.....(if not defined, output.csv will be used): "
                ) or "output.csv"
                is_empty = isNotBlank(filename)
                if is_empty == False:
                    print("Writing to output.csv")
                    df.to_csv(filename, index=False)
                else:
                    print("CSV writing to", filename, "file.")
                    df.to_csv(filename, index=False)
            except ValueError:
                print("Incorrect file name.(probably empty string)")
                exit(0)
            else:
                exit(0)
Esempio n. 33
0
def print_hosts():
    # HOST API URL
    api_url = "https://sandboxapicem.cisco.com/api/v1/host"

    # All APIC-EM REST API request and response content type is JSON.
    ticket = get_ticket()
    headers = {"content-type": "application/json", "X-Auth-Token": ticket}

    resp = requests.get(api_url, headers=headers, verify=False)
    # This is the http request status
    print("Status of /host request: ", resp.status_code)
    # Check if the request status was 200/OK
    if resp.status_code != 200:
        raise Exception("Status code does not equal 200. Response text: " +
                        resp.text)
    # Get the json-encoded content from response
    response_json = resp.json()

    # Now create a list of host info to be held in host_list
    host_list = []
    i = 0
    for item in response_json["response"]:
        i += 1
        host = [i, item["hostType"], item["hostIp"]]
        host_list.append(host)

    table_header = ["#", "Type", "IPv4"]
    #print(tabulate(host_list, table_header))
    print(tabulate(host_list, table_header, tablefmt="grid"))
Esempio n. 34
0
def print_devices():

    api_url = "https://devnetsbx-netacad-apicem-3.cisco.com/api/v1/network-device"

    ticket = get_ticket()

    headers = {"content-type": "application/json", "x-Auth-Token": ticket}

    resp = requests.get(api_url, headers=headers, verify=False)

    print("Status of Host request:", resp.status_code)

    response_json = resp.json()

    devices_list = []
    i = 0

    for item in response_json["response"]:
        i += 1
        host = [i, item["family"], item["type"], item["macAddress"]]
        devices_list.append(host)

    table_header = ["Number", "Family", "Type", "MAC"]

    print(tabulate(devices_list, table_header))
Esempio n. 35
0
def print_devices():
    api_url = "https://sandboxapicem.cisco.com/api/v1/network-device"
    ticket = get_ticket()
    # Hard Code ticket
    # ticket = "ST-3490-ULLpHxvkKX2tro0L710T-cas"

    headers = {
        "content-type": "application/json",
        "X-Auth-Token": ticket
    }

    resp = requests.get(api_url, headers=headers, verify=False)

    print("Status of /host request: ", resp.status_code)

    if resp.status_code != 200:
        raise Exception("Status code does not equal 200. Response text: " + resp.text)

    response_json = resp.json()

    host_list = []
    i = 0
    for item in response_json["response"]:
        i += 1
        host = [i, item["type"], item["managementIpAddress"]]
        host_list.append(host)

    table_header = ["Number", "Type", "IP"]
    print(tabulate(host_list, table_header))
def _test_perf_vector_sum():
    # Outputs:

    #   vector_len    num_of_vectors    reduce      zip
    # ------------  ----------------  --------  -------
    #           10                10   0.00001  0.00000
    #           10               100   0.00015  0.00002
    #           10              1000   0.00183  0.00029
    #           10              5000   0.00913  0.00266
    #           10             10000   0.01617  0.00869
    #          100                10   0.00009  0.00005
    #          100               100   0.00093  0.00021
    #          100              1000   0.00984  0.00400
    #          100              5000   0.06485  0.09937
    #          100             10000   0.14297  0.23023
    #         1000                10   0.00132  0.00056
    #         1000               100   0.01388  0.00429
    #         1000              1000   0.13434  0.11415
    #         1000              5000   0.66533  1.35771
    #         1000             10000   1.42573  3.34425

    # What do we learn from this?

    # The zip implementation starts out faster, but looses out as the size and
    # number of vectors increases. This might have something to do with loss of
    # locality due to iterating over vectors in the inner loop.
    import tabulate

    perf = [(vector_len, num_of_vectors)+_compare_vector_sum_implementations(vector_len, num_of_vectors, number=100)
            for vector_len in (10, 100, 1000)
            for num_of_vectors in (10, 100, 1000, 5000, 10000)]
    print(tabulate(perf, headers='vector_len, num_of_vectors, reduce, zip'.split(', '), floatfmt=".5f"))
Esempio n. 37
0
def AgregarAdministrador(idEmpresa, conn):
    cur = conn.cursor()
    fecha = "{:%d-%m-%Y}".format(datetime.date.today())
    cur.execute(getTrabajadores.format(idEmpresa,fecha))
    trabajadoresActivos = cur.fetchall()
    ImprimirTitulo("Seleccionar trabajador.")
    Imprimir(tabulate(trabajadoresActivos, showindex=range(1,len(trabajadoresActivos)+1)))
    i = len(trabajadoresActivos)+1
    if len(trabajadoresActivos)<1:
        Imprimir("No hay trabajadores. :(")
    Imprimir("{} Volver.\n"
             "{} Salir.".format(i,i+1))
    seleccion = ValidarOpcion(range(1, i+3))
    if seleccion == i:
        return
    elif seleccion == i+1:
        conn.close()
        sys.exit()
    id = SiguienteID("administrador", conn)
    correo_usuario = trabajadoresActivos[seleccion-1][1]
    Activo = True
    cur.execute(agregarAdmin.format(id, idEmpresa, correo_usuario, Activo))
    Imprimir("Administrador agregado.")
    conn.commit()
    cur.close()
    return
Esempio n. 38
0
def table(header, content):
	for rows in content:
		term = rows[0]
		if type(term) == float:
			continue
		term = unicode(term, 'utf-8')
		rows[0] = term

	return tabulate(content, headers=header,tablefmt='orgtbl')
def print_one_dataset(data):
    """
    data is a dict with speed as the key and a dict with info for each speed
    """

    speeds = data.keys()
    speeds.sort()
    datapoints = [ data[key] for key in speeds ]

    print(tabulate(datapoints, headers='keys'))
Esempio n. 40
0
def print_tabulate(res, noheader=False, short=False):
    config = read_config()
    c = conn(config)
    tbl = []
    template_cache = {}
    for i in res:
        if not i.__dict__.has_key('keypair'):
            i.__setattr__('keypair', 'None')
        if not i.__dict__.has_key('password'):
            i.__setattr__('password', 'None')
        if not i.__dict__.has_key('group'):
            i.__setattr__('group', 'None')
        # cache templates
        if not template_cache.has_key(i.templateid):
            # lookup
            t = get_template_from_id(c, i.templateid)
            if t:
                template_cache[i.templateid] = t
            else:
                template_cache[i.templateid] = type('Template', (object,), {'account': 'DELETED'})
        if short:
            tbl.append([i.name])
        else:
            tbl.append([i.name,
                i.zonename,
                i.state,
                i.serviceofferingname,
                i.group,
                i.nics[0].networkname,
                i.nics[0].ipaddress,
                i.keypair,
                i.password,
                "%s/%s" % (template_cache[i.templateid].account, i.templatename),
                i.created]
            )
    tbl = sorted(tbl, key=operator.itemgetter(0))
    if (noheader or short):
        print tabulate(tbl, tablefmt="plain")
    else:
        tbl.insert(0, ['name', 'zone', 'state', 'offering', 'group', 'network', 'ipaddress', 'sshkey', 'password', 'template', 'created'])
        print tabulate(tbl, headers="firstrow")
def AndersonDarlingTest(X):

	print "Andersion Darling Test"
	n = X.shape[1]
	critical_values = [ 0.575, 0.655,  0.786,  0.917,  1.091]
	significance_levels = [ 15.,   10.,    5.,    2.5,   1. ]
	table1 =[]
	table2 = []
	for x,y in zip(critical_values,significance_levels):
		table1.append([x,y])

	print "if A^2 is greater than the critical value for the correspoinding significance level, reject H0"
	print "Critical Value vs Significance level"
	headers1 = ["Critical Value","Significance Level"]
	print tabulate(table1,headers1,tablefmt = "fancy_grid")

	for i in xrange(n):
		results = anderson(X[:,i])	
		row = [features[i],results]
		table2.append(row)

	headers2 = ["Feautres","A^2"]
	print tabulate(table2,headers2,tablefmt = "fancy_grid")
Esempio n. 42
0
    def get_table(self, remove_headers = False):
        from tabulate import tabulate
        iterfields = IterationInfo._fields
        subset_names, prediction_funcs, cost_funcs = zip(*self.score.keys())
        headers = [
            (' ', )*len(iterfields) + subset_names,
            (' ', )*len(iterfields) + prediction_funcs,
            iterfields + cost_funcs
            ]
        data = [v for v in self.info] + self.score.values()
        table = tabulate(headers+[data], tablefmt='plain')
        if remove_headers:
            table = table[table.rfind('\n'):]

        return table
Esempio n. 43
0
 def doFile(self):
     index = self.ui.scriptlist.currentRow()
     b = self._files._files[index]
     self.ui.StatusBox.setText(str(b))
     count = check_comments(b._filename)
     self.ui.linenumbers.setText(str(count._linecount))
     self.ui.commentnumbers.setText(str(count._commentcount))
     self.ui.functionnumbers.setText(str(count._functioncount))
     t = tabulate(b.getResults(), linecount=count._linecount, commentcount=count._commentcount, functioncount=count._functioncount, correctweight= int(self.ui.correctweight.text()), wrongweight = int(self.ui.incorrectweight.text()), errorweight = int(self.ui.errorweight.text()), commentfreq= int(self.ui.comment_freq.text()), functionfreq= int(self.ui.avg_func_len.text()), includeComments= self.ui.commentcheck.checkState(), includeFunctions= self.ui.functioncheck.checkState())
     self.ui.Total_score.setText(str(t.getScore()))
     self.ui.IO_score.setText(str(t.getIOScore()))
     self.ui.correctnum.setText(str(t._correctraw))
     self.ui.errornum.setText(str(t._errorraw))
     self.ui.incorrectnum.setText(str(t._incorrectraw))
     if (self.ui.commentcheck.checkState()):
         self.ui.comment_score.setText(str(t.getCommentScore()))
     else:
         self.ui.comment_score.setText("N/A")
     if (self.ui.functioncheck.checkState()):
         self.ui.Function_score.setText(str(t.getFunctionScore()))
     else:
         self.ui.Function_score.setText("N/A")
Esempio n. 44
0
 def __repr__(self):
     headers = ['Name', 'Club', 'Value', 'Points', 'Position', 'Last date']
     total_points = sum(p.points for p in self.points)
     table = [self.name, self.clubname, self.position, self.prices[-1].price, total_points, self.prices[-1].date]
     return tabulate(table, headers, tablefmt="rst", numalign="right", floatfmt=",.0f")
Esempio n. 45
0
def main():

    
    # 1. Initialize nRounds to 4
    nRounds = 4

    # rankTableA = buildRankTable('groupA')
    # for r in rankTableA:
    #     print (r)

    # 2. Loop for each round
    for r in range(nRounds):
        
        # 2.1 Actions for round 0
        if r == 0:
            
            # Build rank tables of the 4 groups
            rankTableA = buildRankTable('groupA')
            rankTableB = buildRankTable('groupB')
            rankTableC = buildRankTable('groupC')
            rankTableD = buildRankTable('groupD')


            # print rank tables of the 4 groups
            print('***************************************************************')
            print('*              Rank Tables after ROUND 0                      *')
            print('***************************************************************')

            print('\n\nRank table for groupA')
            print(tabulate(rankTableA, headers = ['Team', 'Point', 'Rank']))
            print('\n\nRank table for groupB')
            print(tabulate(rankTableB, headers = ['Team', 'Point', 'Rank']))
            print('\n\nRank table for groupC')
            print(tabulate(rankTableC, headers = ['Team', 'Point', 'Rank']))
            print('\n\nRank table for groupD')
            print(tabulate(rankTableD, headers = ['Team', 'Point', 'Rank']))

            # Groups A and B are corss out to play in round 1
            crossedTableAB = buildCrossedTable(rankTableA, rankTableB)

            # Groups C and D are corss out to play in round 1
            crossedTableCD = buildCrossedTable(rankTableC, rankTableD)

            # Print match tables of next round
            print('\n\nMatches for next round resulting of crossing group A and B')
            print(tabulate(crossedTableAB, headers = ['Team1', 'Team2']))

            print('\n\nMatches for next round resulting of crossing group C and D')
            print(tabulate(crossedTableAB, headers = ['Team1', 'Team2']))
                

        # 2.2 Actions for round 1
        if r == 1:

            # Determine the two winners of group AB, which will play in round 2
            winnerListAB = []
            for i in range(len(crossedTableAB)):
                winnerListAB.append(determineWinner(crossedTableAB[i]))

            # Determine the two winners of group CD, which will play in round 2
            winnerListCD = []
            for i in range(len(crossedTableCD)):
                winnerListCD.append(determineWinner(crossedTableCD[i]))

            # Preparte cross table AB to show results
            if winnerListAB[0] == crossedTableAB[0][0] or winnerListAB[0] == crossedTableAB[0][1]:
                crossedTableAB[0].append(winnerListAB[0])
                crossedTableAB[1].append(winnerListAB[1])
            else:
                crossedTableAB[0].append(winnerListAB[1])
                crossedTableAB[1].append(winnerListAB[0])

            # Preparte cross table CD to show results
            if winnerListCD[0] == crossedTableCD[0][0] or winnerListCD[0] == crossedTableCD[0][1]:
                crossedTableCD[0].append(winnerListCD[0])
                crossedTableCD[1].append(winnerListCD[1])
            else:
                crossedTableCD[0].append(winnerListCD[1])
                crossedTableCD[1].append(winnerListCD[0])

            # Prepare winner list of group AB to show match of next round
            toPrintWinnerListAB = []
            toPrintWinnerListAB.append(winnerListAB)
            

            # Prepare winner list of group CD to show match of next round
            toPrintWinnerListCD = []
            toPrintWinnerListCD.append(winnerListCD)
                   
            # Print winners of crossed table AB
            print('\n\n')
            print('***************************************************************')
            print('*                          ROUND 1                            *')
            print('***************************************************************')
            print('\n\nResults of the matches of the crossed groups A and B')
            print(tabulate(crossedTableAB, headers = ['Team1', 'Team2', 'Winner']))
            
            # Print winners of crossed table CD
            print('\n\nResults of the matches of the crossed groups C and D')
            print(tabulate(crossedTableCD, headers = ['Team1', 'Team2', 'Winner']))

            #Print match table of group AB for next round
            print('\n\nMatch tables of groups A and B for semi-finals')
            print(tabulate(toPrintWinnerListAB, headers = ['Team1', 'Team2']))

            #Print match table of group CD for next round
            print('\n\nMatch tables of groups C and D for semi-finals')
            print(tabulate(toPrintWinnerListCD, headers = ['Team1', 'Team2']))

            
        # 2.3 Actions for round 2 (semi final)
        if r == 2:

            # Detemine the winner and the looser of the two classified teams of group AB
            winnerAB = determineWinner(winnerListAB)
            if winnerAB != winnerListAB[0]:
                loserAB = winnerListAB[0]
            else:
                loserAB = winnerListAB[1]

            # Detemine the winner and the looser of the two classified teams of group CD
            winnerCD = determineWinner(winnerListCD)
            if winnerCD != winnerListCD[0]:
                loserCD = winnerListCD[0]
            else:
                loserCD = winnerListCD[1]

            #Preparte winner list AB to show results
            winnerListAB.append(winnerAB)
            toPrintWinnerListAB = []
            toPrintWinnerListAB.append(winnerListAB)

            #Preparte winner list AB to show results
            winnerListCD.append(winnerCD)
            toPrintWinnerListCD = []
            toPrintWinnerListCD.append(winnerListCD)

            # Prepare match table for final
            toPrintChampionsip = []
            toChampionship = []
            toChampionship.append(winnerAB)
            toChampionship.append(winnerCD)
            toPrintChampionsip.append(toChampionship)

            # Prepare match table for third place
            toPrintThirdPlace = []
            toThirdPlace = []
            toThirdPlace.append(loserAB)
            toThirdPlace.append(loserCD)
            toPrintThirdPlace.append(toThirdPlace)

            # Print winners of winner list AB
            print('\n\n')
            print('***************************************************************')
            print('*                         SEMI FINALS                         *')
            print('***************************************************************')
            print('\n\nResults of the matches of groups A and B in semi-finals')
            print(tabulate(toPrintWinnerListAB, headers = ['Team1', 'Team2', 'Winner']))

            # Print winners of winner list CD
            print('\n\nResults of the matches of groups C and D in semi-finals')
            print(tabulate(toPrintWinnerListCD, headers = ['Team1', 'Team2', 'Winner']))

            #Print match table for championship
            print('\n\nMatch table for championship')
            print(tabulate(toPrintChampionsip, headers = ['Team1', 'Team2']))

            #Print match table for third place
            print('\n\nMatch table for third place')
            print(tabulate(toPrintThirdPlace, headers = ['Team1', 'Team2']))
                       

        # 2.4 Actions for round 3 (final)
        if r ==3:

            # Get champion and sub-champion
            champion = determineWinner([winnerAB, winnerCD])
            if champion != winnerAB:
                subChampion = winnerAB
            else:
                subChampion = winnerCD

            # Get third place
            competitors = []
            competitors.append(loserAB)
            competitors.append(loserCD)
            thirdPlace = determineWinner(competitors)

            # Prepare table to show results of championship match
            toPrintChampionsip = []
            toChampionship.append(champion)
            toPrintChampionsip.append(toChampionship)

            # Prepare table to show results of third place match
            toPrintThirdPlace = []
            toThirdPlace.append(thirdPlace)
            toPrintThirdPlace.append(toThirdPlace)

            # Prepare table for final results
            toPrintFinalResults = []
            finalResults = []
            finalResults.append(champion)
            finalResults.append(subChampion)
            finalResults.append(thirdPlace)
            toPrintFinalResults.append(finalResults)

            #Print results of championship match
            print('\n\n')
            print('***************************************************************')
            print('*                          FINALS                             *')
            print('***************************************************************')
            print('\n\nResults of the championship match')
            print(tabulate(toPrintChampionsip, headers = ['Team1', 'Team2', 'Winner']))

            # Print results of third place match
            print('\n\nesults of the third place match')
            print(tabulate(toPrintThirdPlace, headers = ['Team1', 'Team2', 'Winner']))
            
            # Print final results:
            print('\n\nFinals results:')
            print(tabulate(toPrintFinalResults, headers = ['Champion', 'Sub-Champion', 'Third Place']))

    # 3. Plot statistics of champion, subChampion and thirdPlace
    print('\n\n')
    print('***************************************************************')
    print('*                       Statistics                            *')
    print('***************************************************************')
    print('\n\nDo the results of round 0 coincide with the forecast?')
    print('Let\'s compare the scores of the champion, sub-champion and')
    print('third-place')
    plotGoalsBarChar(finalResults)
def find_pairs(my_input):

    output_path = os.path.join(my_input, "Fastq_matchmaker")
    create_path_if_not_exists(output_path)

    paired_q = raw_input("Do you have paired reads in separate files? [y/n] ")

    if paired_q.lower() == 'n':
        print('Ok, one file per task.')
        data_files = glob.glob(os.path.join(my_input, '*.fastq.gz'))
        # finds any files with fastq.gz extension in folder

    elif paired_q.lower() == 'y':
        print ('Ok, looking for read mates. Mates must be named *_1.fastq.gz and *_2.fastq.gz for pairing.')

        pairs = []
        full_path = []
        easy_read = []

        for forward_file in glob.glob(os.path.join(my_input, '*_1.fastq.gz')):
            forward_path, forward_name = forward_file.rsplit("/", 1)
            sample_id, ext = forward_name.rsplit("_", 1)
            reverse_name = sample_id + '_2.fastq.gz'

            if os.path.isfile(reverse_name) is True:
                pairs.append((forward_name, reverse_name))
                full_path.append((forward_file, os.path.join(forward_path+"/"+reverse_name)))

        for index, item in enumerate(pairs, start=1):
            easy_read.append((index, item))

        table = tabulate(easy_read, headers=["#", "Pair"], tablefmt="grid")
        print (table)

        mates_q = raw_input("Are these pairings correct? [y/n] ")
        if mates_q.lower() != "y":
            print("Run aborted. Double check file names.")
            return
        else:
            print ("Ok saving table to Matchmaker folder")
            filename = os.path.join(output_path, 'table_pairs.txt')
            f = open(filename, 'w')
            f.write(table)
            f.close()

        # correct delimiters for the cluster
        data_files = []
        for i in range(len(full_path)):
            data_files.append(str.join(' ', full_path[i]))

    else:
        print("Run aborted.")
        return

    task_count = len(data_files)
    assert task_count > 0, "Could not find any fastq files in folder %s" % my_input


    list_index=os.path.join(output_path,'read_files.txt')
    f=open(list_index,'w')
    f.write(str(data_files))
    f.close()
    print ("All done! Files are located in %s" %output_path)
def run_star(name, input_path, output_path, step):
    paired_q = raw_input("Do you have paired reads in separate files? [y/n] ")

    if paired_q.lower() == 'n':
        print('Ok, one file per task.')

        data_files = glob.glob(os.path.join(input_path, '*.fastq.gz'))

    elif paired_q.lower() == 'y':
        print ('Ok, looking for read mates. Mates must be labeled *_1.fastq.gz and *_2.fastq.gz for pairing.')

        # build forward and reverse file lists, match pairs
        forward = []
        reverse = []
        for read_file in glob.glob(os.path.join(input_path, '*_2.fastq.gz')):
            reverse.append(read_file)
        for read_file in glob.glob(os.path.join(input_path, '*_1.fastq.gz')):
            forward.append(read_file)

        pairs = []
        for forward_file in forward:
            for reverse_file in reverse:
                for_path, ext_for = forward_file.rsplit("_", 1)
                rev_path, ext_rev = reverse_file.rsplit("_", 1)
                if for_path == rev_path:
                    pairs.append((forward_file, reverse_file))

        # double check correct pairing in  easy to read table
        easy_read = []
        for i in range(len(pairs)):
            path1, name1 = pairs[i][0].rsplit("/", 1)
            path2, name2 = pairs[i][1].rsplit("/", 1)
            easy_read.append((i+1, name1, name2))

        table = tabulate(easy_read, headers=["Pair #", "Forward", "Reverse"], tablefmt="grid")
        print (table)
        mates_q = raw_input("Are these pairings correct? [y/n] ")
        if mates_q.lower() != "y":
            print("Run aborted.")
            return
        else:
            filename = os.path.join(output_path, 'table_pairs.txt')
            f = open(filename, 'w')
            f.write(table)
            f.close()

        data_paired = []
        for i in range(len(pairs)):
            data_paired.append(str.join(' ', pairs[i]))
        data_files = data_paired

    else:
        print("Run aborted.")
        return

    task_count = len(data_files)
    assert task_count > 0, "Could not find any fastq files in folder %s" % input_path

    command = 'input1=${inputs[$SGE_TASK_ID+$SGE_TASK_ID-1]}\n' \
    'input2=${inputs[$SGE_TASK_ID+$SGE_TASK_ID]} \n' \
    'echo "Actual input for this task is:" $input1 $input2 \n' \
    'STAR -runThread %somethings --genomeDir /netapp/home/dreuxj/Annotation/GRCh38_Gencode24/ --readFilesIn $input1 $input2\
    --readFilesCommand gunzip -c --outSAMtype BAM Unsorted --outFilterIntronMotifs RemoveNoncanonical\
    --outFilterType BySJout --outFileNamePrefix $OUT/$SGE_TASK_ID'

    output_path = os.path.join(output_path, '3.STAR')
    create_path_if_not_exists(output_path)
    mem_req = "35G"
    time_req = "99:00:00"
    write_bash_script(name, data_files, output_path, mem_req, time_req, task_count, command, step)