Пример #1
0
def assignMasterSlave(robot1, robot2):

    if robot1.type == robot2.type:
        printc("On ne peut pas permuter 2 " + robot2.type, 'Fail')

    if robot1.type == "Slave":
        slave = Slave(robot1.s, robot1.hostname)
        master = Master(robot2.s, robot2.hostname)
    else:
        slave = Slave(robot2.s, robot2.hostname)
        master = Master(robot1.s, robot1.hostname)
    return master, slave
    def test_correct_number_of_nanoparticles_are_created(self):
        master = Master(100, 1)
        master.create_nanoparticles_and_ligands(10, 1, 1, 1)
        self.assertEqual(10, master.number_of_nanoparticles)

        agents = [i for i in master.agents if isinstance(i, Nanoparticle)]
        self.assertEqual(10, len(agents))
def main():
    master = Master()
    master.start()
    master.join()
    #run()
    print "Server is dead"
    return 0
Пример #4
0
 def loop_Preprocessor(self):
     with open("./pids/preprocessing.pid", "w") as fobj:
         fobj.write(str(os.getpid()))
     workers = Master()
     redis_connector = RedisWrapper()
     worker = PeprocessService(redis_connector, workers, preprocesse_file)
     worker.start_loop()
Пример #5
0
def simul(discipline, rho, k, seed):
    if seed == "-1":
        seed = None
    master = Master()
    results_w, results_w_icl, results_w_icu, \
        results_w_vars, results_w_vars_icl, results_w_vars_icu, \
        results_nq, results_nq_icl, results_nq_icu, \
        results_nq_vars, results_nq_vars_icl, results_nq_vars_icu, \
        execution_time = master.webmain(discipline, rho, k, seed)
    execution_time = "Execution time: {0:.2f} seconds".format(execution_time)
    discipline = "FCFS" if discipline == 1 else "LCFS"
    return render_template("simulation.html",
                           discipline=discipline,
                           rho=rho,
                           results_w=json.dumps(results_w),
                           results_w_icl=json.dumps(results_w_icl),
                           results_w_icu=json.dumps(results_w_icu),
                           results_w_vars=json.dumps(results_w_vars),
                           results_w_vars_icl=json.dumps(results_w_vars_icl),
                           results_w_vars_icu=json.dumps(results_w_vars_icu),
                           results_nq=json.dumps(results_nq),
                           results_nq_icl=json.dumps(results_nq_icl),
                           results_nq_icu=json.dumps(results_nq_icu),
                           results_nq_vars=json.dumps(results_nq_vars),
                           results_nq_vars_icl=json.dumps(results_nq_vars_icl),
                           results_nq_vars_icu=json.dumps(results_nq_vars_icu),
                           execution_time=execution_time)
    def test_two_particles_can_be_far_away(self):
        master = Master(100, 1)
        master.create_nanoparticles_and_ligands(2, 10, 10, 1)
        master.agents[0].position = np.array([1, 1, 1])
        position = np.array([50, 50, 50])

        self.assertTrue(master._check_space_available_nanoparticle(position))
    def test_two_particles_cannot_be_in_same_positions(self):
        master = Master(100, 1)
        master.create_nanoparticles_and_ligands(2, 10, 10, 1)
        master.agents[0].position = np.array([1, 1, 1])
        position = np.array([1, 1, 1])

        self.assertFalse(master._check_space_available_nanoparticle(position))
Пример #8
0
 def loop_Validator(self):
     with open("./pids/validator.pid", "w") as fobj:
         fobj.write(str(os.getpid()))
     workers = Master()
     redis_connector = RedisWrapper()
     worker = ValidatorService(redis_connector, workers, validate_file)
     worker.start_loop()
def main():

    master = Master()
    logging.basicConfig(filename='work.log', level=logging.DEBUG)

    #Init by filling root
    for i in range(0, ROOTCOUNT):
        master.AddRoot(randint(18, 21), 1024)

    #Init
    for i in range(1000):
        #print "Adding node"
        retval = ADD(master)
        #if retval == 2:
        #    print "Added as root"
        #elif retval == 1:
        #    print "Added to some root"
        if retval == 0:
            print "Failed????"

    while True:
        #0 - Insrt
        #1 - Delete
        #2 - Nothing
        #Decide what to do
        choice = randint(0, 2)
        if choice == 0:
            ADD(master)
        elif choice == 1:
            DEL(master)
        else:
            time.sleep(1)
 def test_no_nanoparticles_are_touching(self):
     master = Master(1000, 1)
     master.create_nanoparticles_and_ligands(100, 10, 10, 1)
     positions = [i.position for i in master.agents]
     combs = combinations(positions, 2)
     distance = [np.linalg.norm(a - b) for (a, b) in combs]
     self.assertTrue(all([i > 22 for i in distance]))
Пример #11
0
 def loop_SessionGenerator(self):
     with open("./pids/sessions.pid", "w") as fobj:
         fobj.write(str(os.getpid()))
     workers = Master()
     redis_connector = RedisWrapper()
     worker = SessionGeneratorService(redis_connector, workers,
                                      SessionGeneratorWorker().generate)
     worker.start_loop()
 def test_correct_number_ligands_are_created(self):
     master = Master(100, 1)
     master.create_nanoparticles_and_ligands(100, 10, 1, 1)
     self.assertEqual(master.ligand_length, 1)
     self.assertEqual(master.number_of_ligands, 10)
     ligands = [i.ligands for i in master.agents]
     for l in ligands:
         self.assertEqual(10, len(l))
def preprocesse_file(name):
    with open(name) as fobj:
        lines = fobj.readlines()
    pool = Master()
    results = [x for x in pool.do(lines, preprocessing) if (x is not None) and (len(x) > 2)]
    with open("./preprocessing/"+ name.split("/")[-1], "w") as file:
        file.write(" \n".join(results))
    return "./preprocessing/"+ name.split("/")[-1]
 def test_all_receptors_have_correct_length(self):
     master = Master(100, 1)
     master.create_nanoparticles_and_ligands(10, 1, 1, 1)
     master.create_receptors(10, 1)
     [
         self.assertEqual(1, a.receptor_length) for a in master.agents
         if isinstance(a, Receptor)
     ]
 def test_no_nanoparticles_outside_area(self):
     master = Master(1000, 1)
     master.create_nanoparticles_and_ligands(100, 10, 10, 1)
     positions = [i.position for i in master.agents]
     self.assertTrue(
         all([(i[0] < 1000 and i[1] < 1000 and i[2] < 1000)
              for i in positions]))
     self.assertTrue(
         all([(i[0] > 0 and i[1] > 0 and i[2] > 0) for i in positions]))
 def test_two_particles_cannot_be_touching(self):
     master = Master(100, 1)
     master.create_nanoparticles_and_ligands(2, 10, 10, 1)
     master.agents[0].position = np.array([1, 1, 1])
     position = np.array([23 - 1e-10, 1, 1])
     self.assertFalse(master._check_space_available_nanoparticle(position))
     x = 22 / np.sqrt(3) + 1 - 1e-10
     position = np.array([x, x, x])
     self.assertFalse(master._check_space_available_nanoparticle(position))
Пример #17
0
def validate_file(name):
    with open(name) as fobj:
        lines = fobj.readlines()
    master = Master()
    results = master.do(lines, valid_line)
    print(results)
    print(any(results))
    answer = any(results)
    return answer
Пример #18
0
    def loop_Apriori(self):

        with open("./pids/apriory.pid", "w") as fobj:
            fobj.write(str(os.getpid()))

        workers = Master()
        redis_connector = RedisWrapper()
        worker = AprioriService(redis_connector, workers, None)
        worker.start_loop()
 def test_two_particles_can_be_really_close_without_touching(self):
     master = Master(100, 1)
     master.create_nanoparticles_and_ligands(2, 10, 10, 1)
     master.agents[0].position = np.array([1, 1, 1])
     position = np.array([23, 1, 1])
     self.assertTrue(master._check_space_available_nanoparticle(position))
     x = 22 / np.sqrt(3) + 1
     position = np.array([x, x, x])
     self.assertTrue(master._check_space_available_nanoparticle(position))
Пример #20
0
def binding_energy():
    print('Binding Energy -------------')
    d = np.linspace(5, 25, 5).tolist()
    data = {}
    means = []
    errors = []
    time_data = []
    for i in d:
        variable_finals = []
        for _ in range(3):
            number_of_seconds = 1  # i.e. 1 hour = 3600 seconds
            model = Master(dimension=1000,
                           binding_energy=int(i),
                           time_unit=10e-3,
                           number_of_receptors=2,
                           receptor_length=100,
                           number_of_nanoparticles=1,
                           nanoparticle_radius=50,
                           number_of_ligands=2,
                           ligand_length=7,
                           binding_distance=4,
                           receptor_radius=3,
                           ligand_radius=3,
                           cell_diffusion_coef=1)
            model.create_receptors()  # 100 nm for receptor
            model.create_nanoparticles_and_ligands(
            )  # 1-2 nm for ligand  # 95 particles
            print(
                f'{model.dimension/1000} μm\u00b3 system, {model.binding_energy} binding energy, {model.number_of_nanoparticles} Nanoparticles,\n'
                f'{model.nanoparticle_radius} nm Nanoparticle Radius, {model.number_of_ligands} Ligands, Ligand length {model.ligand_length} nm,\n'
                f'{model.number_of_receptors} Receptors, {model.receptor_length} nm Receptor length, {model.binding_distance} Binding distance'
            )
            model.run(steps=number_of_seconds)  # 3600 for 1 hour
            print(f'The surface coverage is {model.surface_coverage}')
            variable_finals.append(model.surface_coverage)
            time_data.append(np.array(model.coverage))
        mean_time = np.mean(time_data, axis=0)
        error_time = np.std(time_data, axis=0)
        data[f'{model.binding_energy} KT binding energy '] = np.array(
            [list(range(0, model.time + 1)), mean_time, error_time])
        mean_coverage = np.mean(np.array(variable_finals))
        print(f'The mean surface coverage is {mean_coverage}')
        errors.append(np.std(np.array(variable_finals)))
        means.append(np.mean(np.array(variable_finals)))
    plt.xlabel('Time (milliseconds)')
    plt.ylabel('Surface Coverage')
    for key, value in data.items():
        plt.plot(value[0], value[1], label=key)
        plt.fill_between(value[0],
                         value[1] - value[2],
                         value[1] + value[2],
                         alpha=0.2)
    plt.legend()
    plt.show()
    second_variable_plot('Binding energy (kt)', 'Surface Coverage', d, means,
                         errors)
 def test_no_receptor_tips_are_touching(self):
     for _ in range(100):
         master = Master(100, 1)
         master.create_nanoparticles_and_ligands(10, 1, 1, 1)
         master.create_receptors(100, 1)
         positions = [
             a.tip_position for a in master.agents
             if isinstance(a, Receptor)
         ]
         combs = combinations(positions, 2)
         distance = [np.linalg.norm(a - b) for (a, b) in combs]
         [self.assertNotAlmostEqual(d, 0) for d in distance]
 def test_no_receptor_bases_outside_area(self):
     for _ in range(100):
         master = Master(500, 1)
         master.create_nanoparticles_and_ligands(100, 10, 10, 1)
         positions = [
             i.base_position for i in master.agents
             if isinstance(i, Receptor)
         ]
         self.assertTrue(
             all([(i[0] < 1000 and i[1] < 1000 and i[2] < 1000)
                  for i in positions]))
         self.assertTrue(
             all([(i[0] > 0 and i[1] > 0 and i[2] > 0) for i in positions]))
Пример #23
0
def test_AES():
    # INIT KEYS AND PLAINTEXT

    key1 = np.array([[GF2int(randint(0, 255)) for i in range(4)]
                     for j in range(4)],
                    dtype=GF2int)
    key2 = np.array([[GF2int(randint(0, 255)) for i in range(4)]
                     for j in range(4)],
                    dtype=GF2int)
    key3 = np.array([[GF2int(randint(0, 255)) for i in range(4)]
                     for j in range(4)],
                    dtype=GF2int)

    key1 = "".join(format(y, '02x') for x in key1 for y in x)
    key2 = "".join(format(y, '02x') for x in key2 for y in x)
    key3 = "".join(format(y, '02x') for x in key3 for y in x)

    key_cipher = np.array([[GF2int(0) for i in range(4)] for j in range(4)],
                          dtype=GF2int)
    plain_text = np.array([[GF2int(0) for i in range(4)] for j in range(4)],
                          dtype=GF2int)

    plain_text_str = "".join(format(y, '02x') for x in plain_text for y in x)
    key_cipher_str = "".join(format(y, '02x') for x in key_cipher for y in x)

    aes_ref = AES.new(key_cipher_str)
    cipher_ref_str = aes_ref.encrypt(plain_text_str).encode("hex")
    W = aes.ExpandRoundKey(key_cipher)
    master = Master(key_cipher, 4)
    keys = [key1, key2, key3]
    sub = SubCircuit(
        np.array([
            MiniCircuit(keys[s % 3], keys[(s + 1) % 3], W) for s in range(3)
        ]))

    randomness = sub.getCorrRandom()
    shares = [Secret(), Secret(), Secret()]
    for s in range(0, 3):
        shares[s].alpha = randomness[s]
        shares[s].x = plain_text + randomness[(s - 1) % 3]
    W = aes.ExpandRoundKey(key_cipher)
    sub.initShares(shares)
    sub.AES()

    shared = master.reconstructShares(sub)

    state = aes.AES(key_cipher, plain_text)
    if (not np.array_equal(state, shared)):
        return 0
    else:
        return 1
Пример #24
0
def main():

    GPIO.setmode(GPIO.BOARD)

    GPIO.setup(16, GPIO.IN)

    m = Master()

    if GPIO.input(16) == GPIO.HIGH:
        print("Stromlimit erreicht")

    while True:
        m.work()
        time.sleep(0.1)
Пример #25
0
    def __init__(self, ip_address, orders_file_path):
        super(Daemon, self).__init__()

        self.__commands = Commands(orders_file_path)

        self.__master = Master(0, "00:00:00:00:00:00", ip_address, "0", 0)

        self.__master.add_stack(Stack(0,0))

        self.__udp_comm = CommunicatorUDP(42666, self.__master.get_ip_address())

        self.__udp_comm.open_communication()
        print("Master listening on {}:{}".format(ip_address, 42666))
        
        self.__i2c_comm = CommunicatorI2C()
 def __init__(self, clientId, data, verifykey, apiEndPoint):
     self.message = data
     self.sessionkey = verifykey
     self.apiEndPoint = apiEndPoint
     self.splitUrl = apiEndPoint.split('/')
     self.auth = Authentication()
     self.master = Master()
     self.admin = Admin()
     self.role = roleManage()
     self.attendance = attendanceManage()
     self.project = projectManage()
     self.labourer = labbourerManage()
     self.labclass = labourerClass()
     self.shift = shiftManage()
     self.log = Logger()
     self.paymentDesk = paymentDesk()
     self.clientId = clientId
Пример #27
0
    def getListMaster(cursor):

        masters = []

        for (id_master, nm_email, nm_password, nr_killed, nr_life,
             dt_record) in cursor:
            master = Master()
            master.idMaster = id_master
            master.email = nm_email
            master.password = nm_password
            master.killed = nr_killed
            master.life = nr_life
            master.dateRecord = dt_record

            masters.append(master)

        return masters
Пример #28
0
def run_mapred(input_files, map_fn, reduce_fn, output_location):
    # init master and works
    master = Master((HOST, HOST_PORT), MasterHandler)
    clusters = [uid for uid in CLUSTER_TABLE]

    if len(clusters) < 2:
        raise ValueError("Not enough Cluster!")
    # load balance
    mappers_uid, reducers_uid = balance_mapper_reducer(clusters)

    # split files
    input_data = []
    for file in input_files:
        splits = Util.split_file(file_path=file, num_split=len(mappers_uid))
        input_data.append(splits)
    #     print (splits)
    # print (input_data)

    # print ("start!")
    master_args = (master, input_data, mappers_uid, reducers_uid,
                   output_location)
    master_process = multiprocessing.Process(target=master_work,
                                             args=master_args)
    master_process.start()
    # print ("Master Donez!")

    # mapper run
    for uid in mappers_uid:
        mapper = CLUSTER_TABLE[uid]
        mapper_args = (mapper, len(reducers_uid), map_fn)
        mapper_process = multiprocessing.Process(target=mapper_work,
                                                 args=mapper_args)
        mapper_process.start()
    # print ("Mapper setup")

    # reducer run
    for uid in reducers_uid:
        reducer = CLUSTER_TABLE[uid]
        reducer_args = (reducer, reduce_fn)
        reducer_process = multiprocessing.Process(target=reducer_work,
                                                  args=reducer_args)
        reducer_process.start()
Пример #29
0
    def Machine(self, mtype, ip_port, clock_time, logs_file, **kwargs):
        i = 0
        if mtype is 'm':
            master = Master(ip_port, clock_time, logs_file, kwargs['d'],
                            kwargs['slaves_file'])
            while True:
                i += 1
                print("Execution ", i)
                master.get_slaves_time()
                master.calculate_time()
                time.sleep(5)

        elif mtype is 's':
            slave = Slave(ip_port, clock_time, logs_file)
            from rpyc.utils.server import ThreadedServer
            print("Slave machine")
            t = ThreadedServer(slave,
                               port=int(ip_port[ip_port.index(':') + 1:]))
            t.start()
        else:
            print("Option not available")
Пример #30
0
 def __init__(self):
     self.master = Master()
     self.slave = Slave()