Exemplo n.º 1
0
def test_one_epoch(args, model, test_loader):
	model.eval()
	test_loss = 0.0
	pred  = 0.0
	count = 0
	AP_List = []
	GT_Size_List = []
	precision_list = []
	registration_model = Registration(args.reg_algorithm)

	for i, data in enumerate(tqdm(test_loader)):
		template, source, igt, gt_mask = data

		template = template.to(args.device)
		source = source.to(args.device)
		igt = igt.to(args.device)						# [source] = [igt]*[template]
		gt_mask = gt_mask.to(args.device)

		masked_template, predicted_mask = model(template, source)
		result = registration_model.register(masked_template, source)
		est_T = result['est_T']
		
		# Evaluate mask based on classification metrics.
		accuracy, precision, recall, fscore = evaluate_mask(gt_mask, predicted_mask, predicted_mask_idx = model.mask_idx)
		precision_list.append(precision)
		
		# Different ways to visualize results.
		display_results(template.detach().cpu().numpy()[0], source.detach().cpu().numpy()[0], est_T.detach().cpu().numpy()[0], masked_template.detach().cpu().numpy()[0])

	print("Mean Precision: ", np.mean(precision_list))
Exemplo n.º 2
0
 def build(self):
     manager = ScreenManager()
     manager.add_widget(Login(name='login_window'))
     manager.add_widget(Registration(name='register_window'))
     manager.add_widget(HomeWindow(name='home_window'))
     manager.add_widget(SettingsWindow(name='settings'))
     manager.add_widget(GroupWindow(name='group_window'))
     manager.add_widget(NewGroupWindow(name='new_group_window'))
     manager.add_widget(ActivityWindow(name='activity_window'))
     manager.add_widget(NewActivityWindow(name='new_activity_window'))
     manager.add_widget(JoinGroupWindow(name='join_group_window'))
     manager.add_widget(ActivityDetailWindow(name='activity_detail_window'))
     manager.add_widget(PaymentWindow(name='payment_window'))
     manager.add_widget(MyTransactionWindow(name='my_transaction_window'))
     manager.add_widget(ApprovalsWindow(name='approvals_window'))
     manager.add_widget(AddResourcesWindow(name='new_resource_window'))
     manager.add_widget(ResourcesWindow(name='resources_window'))
     manager.add_widget(
         ResourcesHistoryWindow(name='resources_history_window'))
     manager.add_widget(
         DonationsHistoryWindow(name='donations_history_window'))
     self.theme_cls.primary_palette = 'Blue'
     self.theme_cls.theme_style = "Light"
     self.title = "Aaksathe"
     return manager
Exemplo n.º 3
0
Arquivo: VICN.py Projeto: zzali/NDSDN
    def __init__(self, *args, **kwargs):
        super(ICSDNController, self).__init__(*args, **kwargs)
        
#        CONF = cfg.CONF
#        CONF.register_opts([
#            cfg.StrOpt('experimnet', default='ds100ms__dsh_1ms', help = ('The experiment by the parameters'))], group='NETPARAM')
        print (CONF.netparam.exp)
        self.log_file='./Out/' + CONF.netparam.protocol +  '/' + CONF.netparam.exp + '/' + CONF.netparam.smpl 
        if os.path.exists(self.log_file) is not True:
            os.makedirs(self.log_file)
        self.switches = []
        self.links = []
        self.mac_to_port = {}
        self.topology_api_app = self
        self.net = nx.DiGraph()  # Directional graph to set output_port
        self.INTEREST_PROTOCOL = 150
        self.DATA_PROTOCOL = 151
        self.REGISTER_PROTOCOL = 152
        self.HELLO_LABEL = 932620
        f = os.system('ifconfig > ifconfig')
        f = open('ifconfig', 'r+').read()
        # f = open('/proc/net/arp', 'r').read()sc
        mac_regex = re.compile("(?:[0-9a-fA-F]:?){12}")
        self.CONTROLLER_ETH = mac_regex.findall(f)[0]
        
        self.INTEREST_PORT = 9997
        self.DATA_PORT = 9998
        self.RIB = Registration()
        self.switches_dp=dict()
        self.icn_switches = []
        self.packet_in_num = 0
        threading.Thread(target=self.packet_in_rate).start()
Exemplo n.º 4
0
 def create_new_user(self):
     """
     When the sign up button is clicked, open a new window and allow
     the user to create a new account.
     """
     self.create_new_user_dialog = Registration()
     self.create_new_user_dialog.show()
Exemplo n.º 5
0
    def process(self, session, form):
        self.session = session
        self.form = form

        # add school row?
        if 'add_school_row' in self.form:
            self.add_school_row = 1

        # save new school?
        if 'save_new_school' in self.form:

            for f in ['school', 'school_rel', 'grade']:
                if f in self.form and self.form[f].value:
                    self.__dict__[f] = self.form[f].value
                else:
                    self.missing_values.append(f)

            if not self.missing_values:
                Registration().addSchool(self.session.user,
                                         self.form['school_rel'].value,
                                         self.form['school'].value,
                                         self.form['grade'].value)
            else:
                self.add_school_row = 1

        # delete user_school
        if 'delete_user_school' in self.form:
            from userschools import UserSchools
            UserSchools().delete(self.form['delete_user_school'].value)
Exemplo n.º 6
0
 def submit(self):
     rid = RegistrationtDAO.newID()
     did = self.getDoctor()
     pid = self.patient.uid
     time = datetime.now()
     rtype = self.getRType()
     reg = Registration(rid, did, pid, rtype, time, False)
     RegistrationtDAO.add(reg)
     self.tk.destroy()
Exemplo n.º 7
0
    def get_customer(self):
        if self.__customer == []:
            with open(".customer.csv", "r") as customer_file:
                for line in customer_file.readlines():
                    name, mail, ssn, phone = line.split(",")
                    new_customer = Registration(name, mail, ssn, phone)
                    self.__customer.append(new_customer)

        return self.__customer
Exemplo n.º 8
0
 def ui_menu_1(self):
   
     name = input("Name: ")
     mail = input("Email: ")
     ssn = input("Social security number: ")
     if len(ssn) != 10:
         print("Invalid SSN")
         ssn = input("Social security number: ")
     phone = input("Phone number: ")
     new_customer = Registration(name, mail, ssn, phone)
     CustomerRepository.add_customer(self, new_customer)
Exemplo n.º 9
0
 def build(self):
     manager = ScreenManager()
     #getuser4.stuff(getuser.username)
     manager.add_widget(Login(name='login'))
     manager.add_widget(Connected(name='connected'))
     manager.add_widget(Registration(name='registration'))
     manager.add_widget(Recipes(name='recipes'))
     manager.add_widget(Adddish(name='adddish'))
     manager.add_widget(YourDishes(name='yourdishes'))
     manager.add_widget(DeleteRec(name='deleterec'))
     return manager
Exemplo n.º 10
0
def reg():
    if current_user.is_authenticated:
        return redirect(url_for('main_page'))
    form = RegForm()
    if form.validate_on_submit():
        reg = Registration()
        user = User(name=form.name.data, sex=form.sex.data, age=form.age.data, rating=0,
                    location='', info='', picture='', login=form.login.data)
        reg.set_password(user, form.password.data)
        user.save()
        return redirect(url_for('log'))
    return render_template('reg.html', form=form)
Exemplo n.º 11
0
def registration(lvmodel, START_PHASE, image_fns, output_dir, mask_fns):
    """
    Registration of surface mesh point set using Elastix
    Performs 3D image registration and move points based on the computed transform
    Cap the surface mesh with test6_2()
    """
    # compute volume of all phases to select systole and diastole:
    TOTAL_PHASE = len(image_fns)
    ids = list(range(START_PHASE,TOTAL_PHASE)) + list(range(0,START_PHASE))
    #ids = [9, START_PHASE]
    reg_output_dir = os.path.join(output_dir, "registration")
    try:
        os.makedirs(reg_output_dir)
    except Exception as e: print(e)

    register = Registration()
    # Only need to register N-1 mesh
    fixed_im_fn = image_fns[START_PHASE]
    fixed_mask_fn = mask_fns[START_PHASE]
    fn_poly = os.path.join(output_dir, os.path.basename(fixed_im_fn)+'.vtp')
    lvmodel.write_surface_mesh(fn_poly)
    volume = list()
    volume.append([START_PHASE,lvmodel.get_volume()])
    image_output_dir = os.path.join(reg_output_dir, "images")
    for index in ids[:-1]:
        print("REGISTERING FROM %d TO %d " % (START_PHASE, (index+1)%TOTAL_PHASE))
    
        #ASSUMING increment is 1
        moving_im_fn = image_fns[(index+1)%TOTAL_PHASE]
        
        register.update_moving_image(moving_im_fn)
        register.update_fixed_image(fixed_im_fn)
        register.update_fixed_mask(fixed_mask_fn)

        try:
            os.makedirs(os.path.join(image_output_dir))
        except Exception as e: print(e)
        fn_out = os.path.join(os.path.join(reg_output_dir), "verts.pts")

        fn_paras = os.path.join(reg_output_dir, str(START_PHASE)+"to"+str((index+1)%TOTAL_PHASE)+'.txt')
        new_lvmodel = register.polydata_image_transform(lvmodel, fn_out, fn_paras)
        register.write_parameter_map(fn_paras)

        #ASSUMING increment is 1
        fn_poly = os.path.join(output_dir, os.path.basename(moving_im_fn)+'.vtp')
        new_lvmodel.write_surface_mesh(fn_poly)
        volume.append([(index+1)%TOTAL_PHASE,new_lvmodel.get_volume()])

    np.save(os.path.join(output_dir, "volume.npy"), volume)
    return
Exemplo n.º 12
0
 def __init__(self, host, port, start_mongo=True):
     """
     Initializes a resource directory and creates registration, lookup resources.
     :param host: the host where the resource directory is.
     :param port: the port where the resource directory listens.
     """
     CoAP.__init__(self, (host, port))
     self.add_resource('rd/', Registration())
     self.add_resource('rd-lookup/', Lookup())
     self.add_resource('rd-lookup/res', LookupRes())
     self.add_resource('rd-lookup/ep', LookupEp())
     self.start_mongo = start_mongo
     if self.start_mongo:
         self.mongodb = Popen(['mongod', '--config', MONGO_CONFIG_FILE, '--auth'])
Exemplo n.º 13
0
def main():
    """The main function sets up and kicks off all of the listeners"""
    # This restores the Ctrl+C signal handler, normally the loop ignores it
    signal.signal(signal.SIGINT, signal.SIG_DFL)

    # Initialize devices
    loop = asyncio.get_event_loop()
    lid = setup_lid_controller(loop)

    # Initialize queue
    bin_q = asyncio.Queue()

    # Argument setup and parsing
    args = get_args()
    offline = args.offline

    # Registration
    if not offline:
        registration = Registration(config_file_name='test_config.json')
        print('Checking registration...')
        if not registration.is_registered():
            print('No registration found. Creating registration')
            registration.register()
        else:
            print('Registration found')
        config = registration.config

    # Setup pedal events with GPIO
    setup_gpio(loop, bin_q)

    # Schedule the tasks
    tasks = [move_consumer(bin_q, lid)]
    if not offline:
        tasks.append(handler_persistance_warpper(bin_q, config))
    for task in tasks:
        asyncio.ensure_future(task)

    # Setup loop in debug mode to catch anything weird
    loop.set_debug(True)

    # Run event loop forever
    print('Beginning event loop')
    loop.run_forever()
    loop.close()

    # Be nice and cleanup
    GPIO.cleanup()
Exemplo n.º 14
0
    def __init__(self, *args, **kwargs):
        super(ICSDNController, self).__init__(*args, **kwargs)
        self.mac_to_port = {}
        self.topology_api_app = self
        self.net = nx.DiGraph()  # Directional graph to set output_port
        self.INTEREST_PROTOCOL = 150
        self.DATA_PROTOCOL = 151
        self.REGISTER_PROTOCOL = 152
        f = os.system('ifconfig > ifconfig')
        f = open('ifconfig', 'r+').read()
        # f = open('/proc/net/arp', 'r').read()sc
        mac_regex = re.compile("(?:[0-9a-fA-F]:?){12}")
        self.CONTROLLER_ETH = mac_regex.findall(f)[0]

        self.INTEREST_PORT = 9997
        self.DATA_PORT = 9998
        self.RIB = Registration()
Exemplo n.º 15
0
    def ui_menu_3(self):
        
        ssn = input("Enter the Social security number: ")
        CustomerRepository.edit_customer(self)              #Opnar skránna í repoinu og replace-ar upplýsingarnar

        print("You can now change the customers information")
        name = input("Name: ")
        mail = input("Email: ")
        ssn = input("Social security number: ")
        if len(ssn) != 10:
            print("Invalid SSN")
            ssn = input("Social security number: ")

        phone = input("Phone number: ")
        new_customer = Registration(name, mail, ssn, phone)
        
        CustomerRepository.add_customer(self, new_customer)
Exemplo n.º 16
0
 def activity(self):
     speak.Speak("Please Log in")
     login = Login()
     name = login.login_check()
     while name == 0:
         name = login.login_check()
     if name == -1:
         quit(-1)
     elif name[0] == "Friend":
         reg = Registration()
         result = reg.register(name[1])
         if result == -8:
             speak.Speak(
                 "Your details have been updated. Please login again.")
             quit()
     else:
         speak.Speak("Let's get started")
         menu = Menu()
         menu.menu_options(name)
Exemplo n.º 17
0
    def _processSignUp(self):
        # check required fields:
        for field in SIGNUP_FIELDS + ['school']:
            if field not in self.form or not self.form[field].value:
                self.missing_fields.append(field)

        # chech required drop down menus
        for field in ['school_rel', 'grade']:
            if field not in self.form or not int(self.form[field].value):
                self.missing_fields.append(field)

        # sign up error message
        if self.missing_fields:
            self.error_msg += 'Please fill in required fields marked in red'
            self.schoolInfo.missing_values = self.missing_fields
            return

        # email cool?
        email = self.form['email1'].value
        if not valid_email(email):
            self.error_msg += 'Invalid email: %s' % email
            self.missing_fields.append('email1')
            return

        # email already in use?
        results = self.users.getUsers({'email': email})
        if results:
            self.error_msg += 'Email %s already in use, try ' \
                'forgot password.' % email
            self.missing_fields.append('email1')
            return

        # passwords match?
        if self.form['password1'].value != self.form['password2'].value:
            self.error_msg += 'Passwords do not match.'
            self.missing_fields.append('password1')
            self.missing_fields.append('password2')
            return

        # user registration
        user_data = {
            'first_name': self.form['first_name'].value,
            'last_name': self.form['last_name'].value,
            'email': self.form['email1'].value,
            'password': self.form['password1'].value,
            'status_id': USER_STATUS_PENDING
        }
        user_school_data = {
            'school_name': self.form['school'].value,
            'school_relationship_id': self.form['school_rel'].value,
            'original_grade': self.form['grade'].value
        }
        try:
            Registration().add(user_data, user_school_data)
        except Exception, e:
            user_data2 = copy(user_data)
            user_data2['password'] = '******'
            self.logger.error('Unable to register user. user_data: %s; '
                              'school_data: %s; Error (100): %s' %
                              (user_data2, user_school_data, e))
            self.error_msg = 'Oops, there was a problem - Error Code 100'
            return
Exemplo n.º 18
0
 def registration(self):
     self.reg_patients = Registration()
     self.reg_patients.show()
     self.reg_patients.finish.clicked.connect(self.add_patients)
     self.reg_patients.exec()
Exemplo n.º 19
0
 def setUp(self):
     self.register = Registration()
Exemplo n.º 20
0
 def __init__(self):
     super().__init__()
     self.only_public_chats = True
     self.registration = Registration()
Exemplo n.º 21
0
from registration import Registration
from authentication import Authentication
from user import User, Admin
import shelve

reg1 = Registration('*****@*****.**', 'Password1', 'Password1')
reg1.registration()
reg2 = Registration('*****@*****.**', 'Password1', 'Password1')
reg2.registration()

with shelve.open('users') as users:
    for user in users.items():
        print(user)

auth1 = Authentication('*****@*****.**', 'Password1')
auth1.authentication()

user1 = User(auth1.authentication())
user1.add_post('Lorem ipsum')
user1.add_post('Ipsum lorem')
print(user1.get_posts())

auth1.leave_account(user1.current_user)

auth2 = Authentication('*****@*****.**', 'Password1')
auth2.authentication()

user2 = Admin(auth2.authentication())
print(user2.get_users_posts_info())
Exemplo n.º 22
0
    def __init__(self):
        '''инициализирует игру и создает игровые ресурсы'''

        pygame.init()

        self.settings = Settings()
        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption("Cactus evolution")

        self.clicker = Clicker(self)

        self.arrows = pygame.sprite.Group()
        self.game_folder = os.path.dirname(__file__)
        self.sounds_folder = os.path.join(self.game_folder, 'sounds')

        self.passed_time = 0
        self.start_game_time = time.time()
        self.clock = pygame.time.Clock()

        self.stats = GameStats(self)
        self.sb = Scoreboard(self)
        self.au = Authorization(self)

        self.last = None
        self.in_mission = False

        self.time = None
        self.access = False
        self.random_color = None

        self.left = False
        self.right = False
        self.up = False
        self.down = False

        self.current_color = None

        #Создание кнопки Play
        self.play_button = Button(self, "Play")

        self.start_time = None
        self.music_play = False
        self.waiting = True
        self.pause = False

        self.start_countdown = True
        self.timer = False
        #self.timer_h = 1
        self.timer_s = self.settings.timer
        self.timer_tick = None
        self.timer_access = True

        #Меню
        self.menu_access = True
        self.check_start_game = False
        self.menu = Menu(self)
        self.multiplayer_access = False
        self.singleplayer_access = False
        self.shop_access = False
        self.end_access = False

        self.reset_arrows = True
        self.authorization_access = True
        self.user_login = ''
        self.user_password = ''
        self.font = pygame.font.Font(None, 32)
        self.text_surface = None

        self.write_access_login = False
        self.write_access_password = False
        self.login = ''
        self.password = ''
        self.bool_resp = None
        self.without_symb = None

        self.multiplayer_timer = 30
        self.multiplayer_ticks = None
        self.mu = Multiplayer(self)
        self.SSP_access = True
        self.step = None

        self.reg = Registration(self)
        self.reg_access = False

        #Мультиплеер - инфа о игроках и игре
        self.search_game_access = False
        self.end_round = False
        self.interval = 3
        self.start_room = False
        self.CLIENT_ID = None
        self.enemy_id = None
        self.game_data = {}
        self.game_search_ticks = None
        self.game_search_timer = None

        self.search_button = True
        self.choise = False

        self.my_health_loss = 0
        self.enemy_health_loss = 0
        self.my_health = None
        self.enemy_health = 1000
        self.end_multiplayer_game_access = False
        self.rez = ''

        self.shop = Shop(self)
        self.level = None
        self.next_level_exp = None
        self.exp = None
        self.coins = None
        self.singleplayer_coins = 0
        self.multiplayer_coins = 0
        self.multiplayer_add_coins = False
        self.singleplayer_add_coins = False
        self.singleplayer_exp = 0
        self.multiplayer_exp = 0
Exemplo n.º 23
0
from registration import Registration

reg = Registration()

email = input('Input email: ')
password = input('Input password: ')

reg.register(email, password)

Exemplo n.º 24
0
if speed == 's':
    jump_booster = 1

if speed == 'm':
    jump_booster = 2

if speed == 'f':
    jump_booster = 3

print("You chose the {} velocity".format(speed))

arduino_connection = arduino.createConnection(
    '/dev/ttyUSB0')  # Change it for your port here.
arduino.setServoInCenter(arduino_connection)

person1 = Registration()
person1.create_file()
person1.take_photo(0)  # webcam = 0 / video = 1

video_capture = cv2.VideoCapture(0)

fps = FPS()
fps.start()

# Load a sample picture and learn how to recognize it.
target_image = face_recognition.load_image_file(person1.dir)
target_face_encoding = face_recognition.face_encodings(target_image)[0]

# Create arrays of known face encodings and their names
known_face_encodings = [target_face_encoding]
Exemplo n.º 25
0
 def test_getSchoolId(self):
     school_id = Registration()._getSchoolId(SCHOOLNAME)
     self.assertEqual(school_id, SCHOOLID)
Exemplo n.º 26
0
 def __init__(self):
     Command.__init__(self)
     self.registration = Registration()
     self.only_public_chats = True
Exemplo n.º 27
0
from block import Block

from multiprocessing import Process, Manager

from faker import Faker

import logging

DATABASE_WALLETS = pickle.load(open("SAVED_DATABASE_WALLETS.p", "rb"))
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)

FAKE = Faker()

OWN_IP = socket.gethostbyname(socket.gethostname())
OWN_REGISTRATION = Registration(time.time(), OWN_IP)


def get_blockchain_state(bc, host='registrar'):
    """Contacts the registrar to update blockchain."""
    registrar_url = 'http://{}:58333/jsonrpc'.format(host)
    headers = {'content-type': 'application/json'}

    # build payload from registration and saved block hashes
    registration_dict = OWN_REGISTRATION.to_dict()
    block_hash_dict = bc.save_block_hashes_to_dict()
    payload = {**registration_dict, **block_hash_dict}
    response = requests.post(registrar_url,
                             data=json.dumps(payload),
                             headers=headers).json()
    bc.load_blocks_from_dict(response)
Exemplo n.º 28
0
        configuration.serviceport = int(configuration.serviceport) # ensure an int value for the server port
    except Exception as e:
        logging.error("in configfile '%s': serviceport '%s' is not valid (%s)" % (configfile, configuration.serviceport, e) )

    # define metadata that will be shown in the Spring Boot Admin server UI
    metadata = {
        "start": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "description": configuration.servicedescription,
        "about": "%s:%d%s" % (configuration.servicehost, configuration.serviceport, aboutendpoint),
        "written in": "Python"
    }

    # initialize the registation object, to be send to the Spring Boot Admin server
    myRegistration = Registration(
        name=configuration.servicename, 
	serviceUrl="%s:%d" % (configuration.servicehost, configuration.serviceport),
        healthUrl="%s:%d%s" % (configuration.servicehost, configuration.serviceport, healthendpoint), 
        metadata=metadata
    )
    
    # start a thread that will contact iteratively the Spring Boot Admin server
    registratorThread = Registrator(
        configuration.springbootadminserverurl, 
        configuration.springbootadminserveruser,
        configuration.springbootadminserverpassword, 
        myRegistration
    )
    registratorThread.start()

    # start the web service
    app.run(debug=True, port=configuration.serviceport)
import random
from faker import Faker
from patient import Patient, PatientDAO
from doctor import Doctor, DoctorDAO
from registration import Registration, RegistrationtDAO

fake = Faker("zh_CN")
patients = PatientDAO.listAll()
doctors = DoctorDAO.listAll()
for i in range(6000):
    rtypes = ["normal", "pro"]
    done = random.choice([True] * 9 + [False] * 1)
    rid = RegistrationtDAO.newID()
    did = random.choice(doctors).uid
    pid = random.choice(patients).uid
    rtime = fake.date_time_this_month(before_now=True,
                                      after_now=False,
                                      tzinfo=None)
    rtype = random.choice(rtypes)
    reg = Registration(rid, did, pid, rtype, rtime, done)
    print(reg)
    RegistrationtDAO.add(reg)

for doc in doctors:
    print(f"-----------Doctor {doc.name} --------------")
    for reg in RegistrationtDAO.listByDoctor(doc.uid, True):
        print(reg)
    for reg in RegistrationtDAO.listByDoctor(doc.uid, False):
        print(reg)