Пример #1
0
def op_command(ip, command, username, password, port=22):
    """ Purpose: For the -c flag, this function is called. It will connect to a device, run the single specified command, and return the output.
                 Paramiko is used instead of ncclient so we can pipe the command output just like on the CLI.
        Parameters:
            ip          -   String containing the IP of the remote device, used for logging purposes.
            host_name   -   The device host-name for output purposes.
            commands    -   String containing the command to be sent to the device.
            username    -   Username used to log into the device
            password    -   Password is needed because we are using paramiko for this.
    """
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    device = ' -> Command: %s\n' % (command)
    command = command.strip() + ' | no-more\n'
    output = ''
    try:
        ssh.connect(ip, port=port, username=username, password=password)
        stdin, stdout, stderr = ssh.exec_command(command=command, timeout=900)
        stdin.close()
        # read normal output
        while not stdout.channel.exit_status_ready():
            output += stdout.read()
        stdout.close()
        # read errors
        while not stderr.channel.exit_status_ready():
            output += stderr.read()
        stderr.close()
        output = '%s\n%s' % (device, output)
        return output
    except paramiko.AuthenticationException:
        output = '*' * 45 + '\n\nBad username or password for device: %s\n' % ip
        return output
Пример #2
0
def inetd_sockets(max_socks):
    """
    """
    sock = fromfd(stdin.fileno())
    stdin.close()
    stdout.close()
    stderr.close()
    return sock
Пример #3
0
 def return_response(self):
     """ Return request result back to SwiftHLM Proxy Middleware (STATUS)
     or to Asynchronous Distributor (MIGRATION or RECAL) """
     self.logger.debug('Return response to Dispatcher')
     self.logger.debug("Response: %s", json.dumps(self.response_out))
     stdout.write(json.dumps(self.response_out))
     stdout.flush()
     stdout.close()
     self.logger.debug('Exiting Handler')
Пример #4
0
def write(data, filename=None):
    """Write data to file if filename is given, to stdout otherwise"""
    if filename is not None:
        output = open(filename, "w")
    else:
        from sys import stdout as output

    output.write(result)

    if filename is not None:
        output.close()
Пример #5
0
def main():
    line = stdin.readline()
    while (len(line) != 0):
        queries = [int(x) for x in line.split()]
        for v in queries:
            stdout.write(str(ans(v)))

        stdout.write("\n")
        line = stdin.readline()

    stdout.close()
    stdin.close()
Пример #6
0
def main(*test_args):
    args = parse_args()
    stats = StatsGithub(args.repo['owner'],
                        args.repo['name'],
                        args.branch,
                        since=args.since,
                        until=args.until,
                        token=args.token)

    parameters = [
        f"{'Repository:':<32}\n", f"{'- host':<32} {args.repo['host']}\n",
        f"{'- owner':<32} {args.repo['owner']}\n",
        f"{'- name':<32} {args.repo['name']}\n",
        f"{'- branch':<32} {args.branch}\n"
    ]

    if args.since or args.until:
        parameters.append(f"{'Period:':<32}\n")
        if args.since:
            parameters.append(
                f"{'- since:':<32} {args.since.strftime('%Y-%m-%d')}\n")
        if args.until:
            parameters.append(
                f"{'- until:':<32} {args.until.strftime('%Y-%m-%d')}\n")

    stdout.writelines(parameters)

    try:
        opened, closed, oldest = stats.issues()
        stdout.writelines([
            f"{'Issues:':<32}\n", f"{'- opened':<32} {opened}\n",
            f"{'- closed':<32} {closed}\n", f"{'- oldest':<32} {oldest}\n"
        ])

        opened, closed, oldest = stats.pull_requests()
        stdout.writelines([
            f"{'Pull requests:':<32}\n", f"{'- opened':<32} {opened}\n",
            f"{'- closed':<32} {closed}\n", f"{'- oldest':<32} {oldest}\n"
        ])

        contributions = stats.contributions()

        lines = [f"{'Contributors:':<32}\n"]
        if contributions:
            for username, commits in contributions:
                lines.append(f"{'- ' + username:<32} {commits:<8}\n")
        stdout.writelines(lines)
        stdout.close()
    except RateLimitExceededException:
        err = "Количество неавторизованных запросов к GitHub API исчерпано. "
        if not args.token:
            err += "Для увеличения лимита авторизуйтесь с помощью токена."
        stderr.write(err)
Пример #7
0
def main():
    global stdin, stdout
    cond = type(stdin) == str and type(stdin) == str
    if cond:  # use file instead of standard
        stdin = open(stdin, "rt")
        stdout = open(stdout, "wt")
    if METHO == 1:  # method
        func1()
    else:
        func2()
    stdin.close()
    stdout.close()
Пример #8
0
def main():
    T = int(stdin.readline())
    case = 1
    while T > 0:
        arr = [int(x) for x in stdin.readline().split()]
        arr = sorted(arr)

        stdout.write("Case " + str(case) + ": " + str(arr[1]) + "\n")
        case += 1
        T -= 1

    stdout.close()
Пример #9
0
def main():
	T = int(stdin.readline())
	while T > 0:
		word = stdin.readline().strip()
		if len(word) == 5:
			stdout.write("3\n")
		else:
			if ('o' in word and 'n' in word) or ('o' in word and 'e' in word) or ('n' in word and 'e' in word):
				stdout.write("1\n")
			else:
				stdout.write("2\n")

		T -= 1

	stdout.close()
Пример #10
0
def main():
    global ELEMS, ACUMS, ANS, N, KEYS
    setrecursionlimit(50000)
    line = stdin.readline()

    while len(line) != 0:

        ELEMS = [0 for i in range(20)]
        ACUMS = [0 for i in range(20)]
        ANS = list()
        KEYS = {}
        N = 0

        elems = [int(x) for x in line.split()]
        t = elems[0]
        N = elems[1]

        if N == 0:
            break

        for i in range(0, N):
            ELEMS[i] = elems[i + 2]

        for i in range(N - 1, -1, -1):
            if i + 1 == N:
                ACUMS[i] = ELEMS[i]
            else:
                ACUMS[i] = ELEMS[i] + ACUMS[i + 1]

        writer.write("Sums of " + str(t) + ":\n")
        solve(0, "", t)

        if len(ANS) > 0:
            for s in ANS:
                writer.write(s + "\n")
        else:
            writer.write("NONE\n")

        ANS = list()
        KEYS = {}

        line = stdin.readline()

    stdin.close()
    writer.close()
Пример #11
0
def main():
    line = stdin.readline()
    while (len(line) != 0):
        n, w, d, wscoins = [int(x) for x in line.split()]

        # n * (n + 1) / 2
        summ = w * ((n - 1) * (n) / 2)

        # Esto deberia ser cierto si esta la basket en el N
        # Pero curiosamente en el input no es asi, esta malo..
        if summ == wscoins:
            stdout.write(str(n) + "\n")
        else:
            lo = 1
            hi = n
            found = False
            while lo + 1 != hi:
                mid = (lo + hi) >> 1

                tmp = summ - (mid * w) + mid * (w - d)

                if tmp < wscoins:
                    hi = mid
                elif tmp > wscoins:
                    lo = mid
                else:
                    stdout.write(str(mid) + "\n")
                    found = True
                    break
            # Ojo en Busqueda binaria siempre probar con lo al final
            # Porque lo al final no se computa
            if not found:
                # Pruebe con el mismo lo, ya que que si lo + 1 == hi falta probar el mismo lo
                tmp = summ - (lo * w) + lo * (w - d)
                if tmp == wscoins:
                    stdout.write(str(lo) + "\n")
                else:
                    # Si no, es n el resultado final
                    stdout.write(str(n) + "\n")

        line = stdin.readline()

    stdout.close()
    stdin.close()
Пример #12
0
 def wrapper(*args, **kwargs):
     try:
         return f(*args, **kwargs)
     except SystemExit:
         raise
     except:
         print_exc()
         exit(1)
     finally:
         try:
             stdout.flush()
         finally:
             try:
                 stdout.close()
             finally:
                 try:
                     stderr.flush()
                 finally:
                     stderr.close()
Пример #13
0
 def wrapper(*args, **kwargs):
     try:
         return f(*args, **kwargs)
     except SystemExit:
         raise
     except:
         print_exc()
         exit(1)
     finally:
         try:
             stdout.flush()
         finally:
             try:
                 stdout.close()
             finally:
                 try:
                     stderr.flush()
                 finally:
                     stderr.close()
Пример #14
0
def main():
    global G, S, P, C, TOTAL_COMPONENTS, PREORDER
    sys.setrecursionlimit(50000)

    line = stdin.readline()
    while (len(line) != 0):
        N, M = [int(x) for x in line.split()]

        TOTAL_COMPONENTS = 0
        for i in range(1, N + 1):
            G[i] = list()
            PREORDER[i] = -1

        for i in range(M):
            line = stdin.readline().split()
            if line[0] == "1":
                u = int(line[1])
                v = int(line[2])
                G[u].append(v)
            else:
                k = int(line[0])
                for i in range(1, k):
                    u = int(line[i])
                    v = int(line[i + 1])
                    G[u].append(v)
                    G[v].append(u)

        for i in range(1, N + 1):
            if PREORDER[i] == -1:
                gabow(i)

        # If there are more than 1 components then clearly the graph is not strongly connected
        if TOTAL_COMPONENTS != 1:
            stdout.write("NO\n")
        else:
            stdout.write("YES\n")

        line = stdin.readline()

    stdout.close()
Пример #15
0
def main():
    line = stdin.readline()
    while (len(line) != 0):
        R, C = [int(x) for x in line.split()]
        A = [0 for i in range((R * C))]
        offset = 0
        rowIdx = 0
        for i in range(R):
            line = stdin.readline().split()
            for e in line:
                x = int(e)
                if x == R * C:
                    rowIdx = (i + 1)
                    A[offset] = float('inf')
                else:
                    A[offset] = x

                offset += 1

        count = 0
        for i in range(len(A)):
            # Empty square
            if A[i] == float('inf'):
                continue

            for j in range(i + 1, len(A)):
                # Notice nothing is greater than inf so it wont do anything harmful
                if A[i] > A[j]:
                    count += 1

        tot = count + rowIdx
        if tot % 2 == 0:
            stdout.write("Y\n")
        else:
            stdout.write("N\n")

        line = stdin.readline()

    stdout.close()
    stdin.close()
Пример #16
0
def evol_search(query, **kwargs):

    import prody
    from os.path import join, split

    pfam_results = prody.searchPfam(query, **kwargs)
    if pfam_results is None:
        return
    outname = kwargs.get('outname', None)
    delimiter = kwargs.get('delimiter', '\t')
    if outname:
        folder, outname = split(outname)
        filepath = join(prody.utilities.makePath(folder), outname)
        out = open(filepath, 'wb')
    else:
        from sys import stdout as out
    title = delimiter.join(['acc', 'id', 'type', 'e-value']) + '\n'
    out.write(title)
    for key in pfam_results:
        val = pfam_results[key]
        evalue = ''
        for i, location in enumerate(val.get('locations', [])):
            temp = location.get('evalue', None)
            if temp:
                if i == 0:
                    evalue = float(temp)
                else:
                    if float(temp) < evalue:
                        evalue = float(temp)
        output = delimiter.join([
            val.get('accession', '    '),
            val.get('id', '    '),
            val.get('type', '    '),
            str(evalue)
        ]) + '\n'
        out.write(output)
    if outname:
        prody.LOGGER.info('Search results written in {0}.'.format(filepath))
        out.close()
Пример #17
0
def main():
	text = stdin.readline().strip()
	case = 1
	while text != "#":
		language = "UNKNOWN"
		if text == "HELLO":
			language = "ENGLISH"
		elif text == "HOLA":
			language = "SPANISH"
		elif text == "HALLO":
			language = "GERMAN"
		elif text == "BONJOUR":
			language = "FRENCH"
		elif text == "CIAO":
			language = "ITALIAN"
		elif text == "ZDRAVSTVUJTE":
			language = "RUSSIAN"

		stdout.write("Case " + str(case) + ": " + language + "\n")
		case += 1
		text = stdin.readline().strip()

	stdout.close()
Пример #18
0
def evol_search(query, **kwargs):

    import prody
    from os.path import join, split

    pfam_results =  prody.searchPfam(query, **kwargs)
    if pfam_results is None:
        return
    outname = kwargs.get('outname', None)
    delimiter = kwargs.get('delimiter', '\t')
    if outname:
        folder, outname = split(outname)
        filepath = join(prody.utilities.makePath(folder), outname)
        out = open(filepath, 'wb')
    else:
        from sys import stdout as out
    title = delimiter.join(['acc', 'id', 'type', 'e-value']) + '\n'
    out.write(title)
    for key in pfam_results:
        val = pfam_results[key]
        evalue = ''
        for i, location in enumerate(val.get('locations', [])):
            temp = location.get('evalue', None)
            if temp:
                if i==0:
                    evalue = float(temp)
                else:
                    if float(temp) < evalue:
                        evalue = float(temp)
        output = delimiter.join([val.get('accession', '    '),
                                 val.get('id', '    '),
                                 val.get('type', '    '),
                                 str(evalue)]) + '\n'
        out.write(output)
    if outname:
        prody.LOGGER.info('Search results written in {0}.'.format(filepath))
        out.close()
Пример #19
0
def evol_search(query, **kwargs):

    import prody
    from os.path import join, split

    pfam_results = prody.searchPfam(query, **kwargs)
    if pfam_results is None:
        return
    outname = kwargs.get("outname", None)
    delimiter = kwargs.get("delimiter", "\t")
    if outname:
        folder, outname = split(outname)
        filepath = join(prody.utilities.makePath(folder), outname)
        out = open(filepath, "wb")
    else:
        from sys import stdout as out
    title = delimiter.join(["acc", "id", "type", "e-value"]) + "\n"
    out.write(title)
    for key in pfam_results:
        val = pfam_results[key]
        evalue = ""
        for i, location in enumerate(val.get("locations", [])):
            temp = location.get("evalue", None)
            if temp:
                if i == 0:
                    evalue = float(temp)
                else:
                    if float(temp) < evalue:
                        evalue = float(temp)
        output = (
            delimiter.join([val.get("accession", "    "), val.get("id", "    "), val.get("type", "    "), str(evalue)])
            + "\n"
        )
        out.write(output)
    if outname:
        prody.LOGGER.info("Search results written in {0}.".format(filepath))
        out.close()
Пример #20
0
from sys import argv, stdout, stdin, stderr
import theano
import time
from ape.timings.computation.run import debugprint, collect_inputs, comptime_run

mode = theano.compile.mode.get_default_mode()
mode = mode.excluding('gpu')


def time_computation(inputs, outputs, numeric_inputs, niter):

    f = theano.function(inputs, outputs, mode=mode)

    starttime = time.time()
    debugprint("Computing")
    for n in xrange(niter):
        outputs = f(*numeric_inputs)
    endtime = time.time()
    duration = endtime - starttime

    return duration / niter


if __name__ == '__main__':

    known_shapes, niter, fgraphs = collect_inputs(argv, stdin)
    results = comptime_run(known_shapes, niter, fgraphs, time_computation)

    stdout.write(str(results))
    stdout.close()
Пример #21
0
num_to_name = {p[0]: p[1] for p in people}
for p in people:
    output_lines.append("NODE\t%s\t%s" % (p[1], ','.join(p[2:])))

# parse contacts
if args.contacts.lower().endswith('.gz'):
    lines = gopen(args.contacts).read().decode().splitlines()
else:
    lines = open(args.contacts).readlines()
for l in lines:
    if l[0] == '\t':
        continue
    s, e, u, v = [x.strip() for x in l.split('\t')[1:5]]
    output_lines.append("EDGE\t%s\t%s\t%s,%s\tu" %
                        (num_to_name[u], num_to_name[v], s, e))

# write to output
if args.output.lower().endswith('.gz'):
    f = gopen(args.output, 'wb', 9)
    f.write('\n'.join(output_lines).encode())
    f.write(b'\n')
    f.close()
else:
    if args.output.lower() == 'stdout':
        from sys import stdout as f
    else:
        f = open(args.output, 'w')
    f.write('\n'.join(output_lines))
    f.write('\n')
    f.close()
Пример #22
0
stdin = open('A-large-practice.in', 'r')
#stdout = open('A-small.out', 'w')
stdout = open('A-large.out', 'w')

T = int(stdin.readline().strip())

for t in range(0, T):

    (A, N) = [int(x) for x in stdin.readline().strip().split()]

    m = [int(x) for x in stdin.readline().strip().split()]

    ans = N

    op = 0

    m.sort()

    while A > 1 and len(m) > 0:
        while A <= m[0]:
            A += A - 1
            op += 1
        A += m[0]
        m[0:1] = []
        ans = min(ans, op + len(m))

    stdout.write('Case #{0}: {1}\n'.format(t+1, ans))

stdin.close()
stdout.close()
def enablePrint() -> None:
    global stdout
    stdout.close()
    stdout = __stdout__
Пример #24
0
                        help="Output File (FASTA format)")
    args = parser.parse_args()
    if args.input == 'stdin':
        from sys import stdin as infile
    else:
        infile = open(args.input)
    if args.output == 'stdout':
        from sys import stdout as outfile
    else:
        outfile = open(args.output, 'w')

    # create mask regions
    mask = False
    for line in infile:
        chrom, pos, depth = line.strip().split('\t')
        chrom = chrom.strip()
        pos = int(pos)
        depth = int(depth)
        if depth < args.min_depth:
            if not mask:  # starting a mask region
                mask = True
                outfile.write('%s\t%d\t' % (chrom, pos))
        else:
            if mask:  # ending a mask region
                mask = False
                outfile.write('%d\n' % (pos - 1))
    if mask:  # close trailing mask region
        mask = False
        outfile.write('%d\n' % pos)
    outfile.close()