Пример #1
0
 def make_questions(self,valid,invalid,valid_history,invalid_history):
     valid_num=random.randint(5,10)
     invalid_num=15-valid_num
     valids=[(x,True) for x in get_n(valid_num,valid,valid_history)]
     invalids=[(x,False) for x in get_n(invalid_num,invalid,invalid_history)]
     l=valids+invalids
     random.shuffle(l)
     return l
Пример #2
0
 def start_game(self,func):
     self.func=func
     self.input_chain.func=self.func
     self.valids,self.invalids=get_valid_invalid(func)
     valids_sample=get_n(7,self.valids)
     invalids_sample=get_n(7,self.invalids)
     self.valid_history.reset()
     self.invalid_history.reset()
     for e in valids_sample:
         self.valid_history.add(e)
     for e in invalids_sample:
         self.invalid_history.add(e)
     self.to_game_mode()
        sys.exit()

    sys.stdout.write(sock.recv(4096) + 'start\n')
    sock.send('start\n')

    input_data = ''
    sys.stdout.write(sock.recv(4096))
    while True:
        data = sock.recv(4096)
        if not data:
            print('-' * 20 + ' Connection closed ' + '-' * 20)
            break
        else:
            sys.stdout.write(data)
            if 'A resposta é:' in data:
                input_data += data

                n = get_n(input_data)

                resp = '%d\n' % (solver(n))
                sys.stdout.write(resp)
                sock.send(resp)

                input_data = ''
            elif 'HACKAFLAG{' in data:
                break
            else:
                input_data += data

    sock.close()
        sys.exit()

    sys.stdout.write(sock.recv(4096) + 'start\n')
    sock.send('start\n')

    input_data = ''
    sys.stdout.write(sock.recv(4096))
    while True:
        data = sock.recv(4096)
        if not data:
            print('-' * 20 + ' Connection closed ' + '-' * 20)
            break
        else:
            sys.stdout.write(data)
            if 'A resposta é:' in data:
                input_data += data

                valor = get_n(input_data)

                resp = '%d\n' % (n_bugs(valor))
                sys.stdout.write(resp)
                sock.send(resp)

                input_data = ''
            elif 'HACKAFLAG{' in data:
                break
            else:
                input_data += data

    sock.close()
Пример #5
0
import lorem
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.serialization.base import Encoding, PublicFormat, NoEncryption

import constants
import utils

if __name__ == "__main__":
    print("Creating a random document...")
    # creating a new 2048 bit rsa key
    print("Creating a new 2048 bit RSA key...")
    sk = utils.new_rsa_key(2048)
    pk = sk.public_key()
    print("the key has N = {} and e = {}".format(utils.get_n(pk),
                                                 utils.get_e(pk)))
    print("Creating a random latin-like sentence...")
    doc = lorem.sentence()
    print("Encrypting sentence...")
    cipheredDoc = sk.public_key().encrypt(
        doc.encode(),
        padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                     algorithm=hashes.SHA256(),
                     label=None))
    with open(constants.PLAINTEXT_PATH, 'w') as f:
        print("Saving plain text version of text...")
        f.write(doc)
    with open(constants.PUBLIC_KEY_PATH, 'wb') as f:
        print("Saving public key...")
        f.write(sk.public_key().public_bytes(Encoding.PEM, PublicFormat.PKCS1))
    with open(constants.CIPHERED_PATH, 'wb') as f:
Пример #6
0
import decimal
from decimal import Decimal
from math import sqrt

from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding

import constants
import utils

if __name__ == "__main__":
    pk = utils.load_public_key_file(constants.PUBLIC_KEY_PATH)
    ctx = decimal.getcontext()
    ctx.prec = 1 << 12
    print("precision is {}".format(ctx.prec))
    n = Decimal(utils.get_n(pk), ctx)
    n_sqrt = n.sqrt(ctx).to_integral_exact()
    p = 0
    q = 0
    print("Finding factors")
    i = 0
    while True:
        i += 1
        if i % 10000 == 0:
            print("try n° {}, we are in {}".format(i, n_sqrt))
        if n % n_sqrt == 0:
            q = n_sqrt
            print("found first factor!", q)
            break
        n_sqrt += 1
    p = n // q
Пример #7
0
def get_TPI(b1vec, c1_guess, ss_params, params):
    t1=time.time()

    # r_guess: guess of interest rate path from period 1 to T1
    beta, sigma, S, l_ub, b, upsilon, chi, A, alpha, delta, tpi_max_iter, tpi_tol, xi_tpi, T1, T2 = params
    r_ss, w_ss, c_ss, n_ss, b_ss, K_ss, L_ss = ss_params
    abs_tpi = 1
    tpi_iter = 0
    rpath_old = np.zeros(T2 + S - 1)
    rpath_old[:T1] = get_path(r_ss, r_ss, T1, 'quadratic')
    rpath_old[T1:] = r_ss
    while abs_tpi > tpi_tol and tpi_iter < tpi_max_iter:
        tpi_iter += 1
        wpath_old = utils.get_w(rpath_old, (A, alpha, delta))
        bmat = np.zeros((S, T2 + S - 1))
        bmat[:, 0] = b1vec
        bmat[:, T2:] = numpy.matlib.repmat(b_ss, S - 1, 1).T
        nmat = np.zeros((S, T2 + S - 1))
        nmat[:, T2:] = numpy.matlib.repmat(n_ss, S - 1, 1).T
        cmat = np.zeros((S, T2 + S - 1))
        cmat[:, T2:] = numpy.matlib.repmat(c_ss, S-1, 1).T
        # Solve the incomplete remaining lifetime decisions of agents alive
        # in period t=1 but not born in period t=1
        for p in range(S): # p is remaining periods of life
            c1_args = (rpath_old[:p + 1], wpath_old[:p + 1], beta, sigma, l_ub, b, upsilon, p + 1, b1vec[S - p - 1], chi[S-p-1:])
            result_c1 = opt.root(utils.get_b_last, c1_guess, args = (c1_args))
            if result_c1.success:
                c1 = result_c1.x
            else:
                raise ValueError("failed to find an appropriate initial consumption")
            # Calculate aggregate supplies for capital and labor
            cvec = utils.get_c(c1, rpath_old[:p + 1], beta, sigma, p + 1)
            # print (np.shape(cvec))
            nvec = utils.get_n(cvec, sigma, l_ub, b, upsilon, wpath_old[:p + 1], p + 1,chi[S-p-1:])
            bvec = utils.get_b(cvec, nvec, rpath_old[:p + 1], wpath_old[:p + 1], p + 1, bs = b1vec[S - p - 1])[1:]
            # Insert the vector lifetime solutions diagonally (twist donut)
            DiagMaskbp = np.eye(p)
            bp_path = DiagMaskbp * bvec
            bmat[S - p:, 1:p + 1] += bp_path

            DiagMasknp = np.eye(p + 1)
            np_path = DiagMasknp * nvec
            nmat[S - p - 1:, :p + 1] += np_path

            DiagMasknp = np.eye(p + 1)
            c_path = DiagMasknp * cvec
            cmat[S - p - 1:, :p + 1] += c_path

        # Solve for complete lifetime decisions of agents born in periods
        # 1 to T2 and insert the vector lifetime solutions diagonally (twist
        # donut) into the cpath, bpath, and EulErrPath matrices
        for t in range(1, T2):
            c1_args = (rpath_old[t: S + t], wpath_old[t: S + t], beta, sigma, l_ub, b, upsilon, S, 0.0, chi)
            result_c1 = opt.root(utils.get_b_last, c1_guess, args = (c1_args))
            if result_c1.success:
                c1 = result_c1.x
            else:
                raise ValueError("failed to find an appropriate initial consumption")
            # Calculate aggregate supplies for capital and labor
            cvec = utils.get_c(c1, rpath_old[t : S + t], beta, sigma, S)
            nvec = utils.get_n(cvec, sigma, l_ub, b, upsilon, wpath_old[t: S + t], S, chi)
            bvec = utils.get_b(cvec, nvec, rpath_old[t: S + t], wpath_old[t: S + t], S)
            # print ("nvec,cvec,bvec: {}".format(np.shape(nvec),np.shape(cvec),np.shape(bvec)))
            DiagMaskbt = np.eye(S)
            bt_path = DiagMaskbt * bvec
            bmat[:, t: t + S] += bt_path

            DiagMasknp = np.eye(S)
            np_path = DiagMasknp * nvec
            nmat[:, t: t + S] += np_path

            DiagMasknp = np.eye(S)
            c_path = DiagMasknp * cvec
            cmat[:, t: t + S] += c_path

        bmat[:, T2:] = np.matlib.repmat(b_ss, S - 1, 1).T
        nmat[:, T2:] = np.matlib.repmat(n_ss, S - 1, 1).T
        cmat[:, T2:] = np.matlib.repmat(c_ss, S - 1, 1).T

        K = utils.get_K(bmat)[0]
        L = utils.get_L(nmat)[0]
        Y = utils.get_Y(K, L, (A, alpha))
        C = utils.get_C(cmat)

        rpath_new = utils.get_r(K, L, (A, alpha, delta))

        # Calculate the implied capital stock from conjecture and the error
        abs_tpi = ((rpath_old[:T2] - rpath_new[:T2]) ** 2).sum()
        # Update guess
        rpath_old[:T2] = xi_tpi * rpath_new[:T2] + (1 - xi_tpi) * rpath_old[:T2]

        print('iteration:', tpi_iter, ' squared distance: ', abs_tpi)
    b_last = abs(bmat[S - 1, :]).max()
    b_err = abs(utils.get_b_errors(cmat[:, :T2 + S - 1], rpath_old[:T2 + S - 1], beta, sigma)).max()
    n_err = abs(utils.get_n_errors(nmat[:, :T2 + S - 1], cmat[:, :T2 + S - 1], sigma, l_ub, b,
                                   upsilon, wpath_old[:T2 + S - 1], chi[0] * np.ones(T2 + S - 1))).max()
    cnt_err = abs(Y[:-1] - C[:-1] - K[1:] + (1 - delta) * K[:-1]).max()
    t2=time.time()
    t=t2-t1
    print (f'It took {t} seconds to solve TPI.')

    k_first = [k for k in K if abs(k - K_ss) < 0.0001][0]
    T_1 = np.where(K == k_first)[0][0]

    return rpath_old, wpath_old, K, L, bmat, nmat, cmat, b_last, b_err, n_err, cnt_err, T_1