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()
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))
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()
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)
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
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)
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()
class RegisterCommand(Command): def __init__(self): Command.__init__(self) self.registration = Registration() self.only_public_chats = True def run(self): user = self.last_update.message.from_user chat = self.last_update.message.chat name = self.get_display_name(user) if self.registration.is_user_registered(chat, user): self.reply_with_text(f"{name} уже зарегистрирован") else: self.registration.register(chat, user) self.reply_with_text( f'Теперь ты зарегистрирован в пидоре дня, {name}')
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()
class RegistrationTest(unittest.TestCase): def setUp(self): self.register = Registration() def test_register_creation(self): self.assertIsInstance(self.register, Registration) def test_user_bio_length(self): self.register.add('*****@*****.**', 'john', 'mike') self.assertEqual(self.register.user_bio_length(self.register.user_bio), 1) def test_add_user(self): self.register.add('*****@*****.**', 'John doe', 'mike') self.assertEqual(len(self.register.user_bio), 1) # def test_check_file_exist(self): # pass # def test_add_member(self): # pass def test_missing_key(self): with self.assertRaises(KeyError): self.register.get_email('*****@*****.**') @unittest.skip('WIP') def test_unknown_method(self): pass #self.assertEqual(self.register.some_method(), 1)
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()
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
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)
class PidorCommand(Command): def __init__(self): super().__init__() self.only_public_chats = True self.registration = Registration() def run(self): chat = self.last_update.message.chat if self.need_to_choose(chat): self.choose_user(chat) else: self.show_last_winner(chat) def choose_user(self, chat): users = self.registration.get_registered_users_for_chat(chat) print(len(users)) successful = False user_id = 0 while not successful: index = random.randrange(0, len(users)) user_id = list(users)[index] try: member = self.bot.getChatMember(chat.id, user_id) successful = True except TelegramError: continue name = self.get_display_name(member.user) self.registration.reward_user(chat, member.user, name) self.reply_with_text(f"Выбираю пидора дня...") self.reply_with_text(f"TODO: Сделать побольше сообщений") self.reply_with_text(f'Ты пидор дня, {name}, поздравляю!') def show_last_winner(self, chat): winner = self.registration.get_last_winner(chat) if len(winner) == 0: self.reply_with_text("О нет! Не могу получить победителя.") else: self.reply_with_text(f"Пидор дня – {winner}") def need_to_choose(self, chat): drawing_time = self.registration.get_last_drawing_time(chat) current_time = time() return current_time - drawing_time > 24 * 60 * 60
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)
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
def register(request): nonlocal registration_list if registration_list: last_registration = registration_list[-1] payload = last_registration.to_dict() else: payload = {"addrMe": None} request_data = json.loads(request.data) new_registration = Registration.from_dict(request_data) registration_list.append(new_registration) return Response(json.dumps(payload), mimetype='application/json')
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'])
def register(request): nonlocal registration_list request_data = json.loads(request.data) new_registration = Registration.from_dict(request_data) new_ip = new_registration.addrMe reg_found = False for registration in registration_list: if registration.addrMe == new_ip: reg_found = True break if not reg_found: registration_list.append(new_registration) # only send blocks that client didn't know about payload = bc.save_blocks_to_dict(request_data) return Response(json.dumps(payload), mimetype='application/json')
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)
def register_view(request, error=False): """ Handles requests to /register If it's a post request, that means we're receiving the form data and we call the form_submission function to save it and return the appropriate page (either the registration page if an error occurs otherwise sends the user to the confirmation page). Otherwise, just returns the registration page. """ if request.method == 'POST': return form_post(request) else: return form_view(request, { 'open': Registration.is_open(), 'error': error })
class StatsCommand(Command): first_places_formats = [ "🌟 *{}* 🌟 – мега-пидор, был пидором дня {} раз(а)", "⭐️ *{}* ⭐️ – почти всем пидорам пидор, был пидором дня {} раз(а)", "✨ *{}* ✨ – уважаемый в широких кругах пидор, был пидором дня {} раз(а)", ] def __init__(self): super().__init__() self.only_public_chats = True self.registration = Registration() def __get_format_string(self, place): if place < len(self.first_places_formats): return self.first_places_formats[place] else: return str(place + 1) + '. {} – {}' def run(self): chat = self.last_update.message.chat users = self.registration.get_registered_users_for_chat(chat) wins = sorted(users, key=lambda key: users[key]['wins'], reverse=True)[:10] usernames = {user: self.get_username(chat, user) for user in wins} lines = [ self.__get_format_string(place).format(usernames[user], str(users[user]['wins'])) for place, user in enumerate(wins) if users[user]['wins'] > 0 ] text = "\n".join(lines) self.reply_with_markdown(text) def get_username(self, chat, user_id): try: user = self.bot.get_chat_member(chat.id, user_id).user return self.get_display_name(user) except TelegramError: return 'Ноунейм'
def __init__(self): super().__init__() self.only_public_chats = True self.registration = Registration()
def test_register(self): register = Registration() profile = register.create_profile('*****@*****.**', 'Password29', profile_id=319955720) self.assertTrue(isinstance(profile, Profile))
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())
def test_new_registration_logging_in(self): profile = Registration().create_profile('*****@*****.**', 'Password29', profile_id=319955720) profile.log_in() self.assertTrue(profile.is_logged_in())
def form_failure(request, error_message): return form_view(request, { 'open': Registration.is_open(), 'error': error_message })
def registration(self): self.reg_patients = Registration() self.reg_patients.show() self.reg_patients.finish.clicked.connect(self.add_patients) self.reg_patients.exec()
def test_new_registration_with_custom_details(self): profile = Registration().create_profile() profile.log_in() self.assertTrue(profile.is_logged_in()) pass
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)
class ICSDNController(app_manager.RyuApp): OFP_VERSIONS = [ofproto_v1_4.OFP_VERSION] ''' This file implement the controller. Ryu is an event-driven controller that you can handle events separately. ============================== =========== Events =========== Events are defined with a python decorator "@set_ev_cls" and it takes two arguments: - Event: (EventOFPxxxxx) + EventOFPSwitchFeatures: Controller response on switch establishment + EventOFPPacketIn: Controller receive message from a switch - Event argument: + CONFIG_DISPATCHER: Ignore events before handshake ============================== ========= Parameters ========= In this section important parameters are described: - datapath: Controller-switch negotiation path - datapath.ofproto: OpenFlow definitions - datapath.ofproto_parser: Wire message for encoder/decoder ============================== ======== Our protocol ======== -- get "protocol" field in IP header -- case protocol: ---- 150 : NDN interest packet ---- 151 : NDN data packet ---- else: other tcp/ip packets ''' 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() # self.nodes = {} # self.links = {} # self.no_of_nodes = 0 # self.no_of_links = 0 # self.i = 0 def packet_in_rate(self): T = float(10) f = open(self.log_file+'/controller_log','w') f.close() pre_num = 0 while (True): time.sleep(T) rate = (self.packet_in_num - pre_num)/T pre_num = self.packet_in_num f = open(self.log_file+'/controller_log','a') print(rate,file=f) f.close() @set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER) def switch_features_handler(self, ev): """ Handle switch features reply to install table miss flow entries. TIP: You can keep this function without any change and reuse it. :param ev: Event :return: """ datapath = ev.msg.datapath ofproto = datapath.ofproto parser = datapath.ofproto_parser self.switches_dp.update({datapath.id:datapath}) if datapath.id in self.icn_switches: print("insert initial rules in ICN switch "+str( datapath.id)) # install table-miss flow entry # # We specify NO BUFFER to max_len of the output action due to # OVS bug. At this moment, if we specify a lesser number, e.g., # 128, OVS will send Packet-In with invalid buffer_id and # truncated packet data. In that case, we cannot output packets # correctly. The bug has been fixed in OVS v2.1.0. match = parser.OFPMatch() # Match everything actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER, ofproto.OFPCML_NO_BUFFER)] ''' Add a flow(role) with priority 0 (lowest priority) in order to send mismatched requests to the controller ''' self.add_flow(datapath, 0, 0, match, actions) self.add_flow(datapath, 1, 0, match, actions) self.add_flow(datapath, 2, 0, match, actions) self.add_flow(datapath, 3, 0, match, actions) # Add a role to goto table 1 for first interest packets from clients # and goto table 2 for other INT and Data packets ins = [parser.OFPInstructionGotoTable(table_id=1)] match = parser.OFPMatch(eth_type=ether_types.ETH_TYPE_MPLS) self.add_flow(datapath, 0, 2, match, None, instruction=ins) ins = [parser.OFPInstructionGotoTable(table_id=2)] match = parser.OFPMatch(eth_type=ether_types.ETH_TYPE_IP,ip_proto=self.INTEREST_PROTOCOL) self.add_flow(datapath, 0, 2, match, None, instruction=ins) match = parser.OFPMatch(eth_type=ether_types.ETH_TYPE_IP,ip_proto=self.DATA_PROTOCOL) self.add_flow(datapath, 0, 2, match, None, instruction=ins) ins = [parser.OFPInstructionGotoTable(table_id=3)] match = parser.OFPMatch(eth_type=ether_types.ETH_TYPE_IP,ip_proto=self.INTEREST_PROTOCOL) self.add_flow(datapath, 2, 1, match, None, instruction=ins) match = parser.OFPMatch(eth_type=ether_types.ETH_TYPE_IP,ip_proto=self.DATA_PROTOCOL) self.add_flow(datapath, 2, 1, match, None, instruction=ins) # # ins = [parser.OFPInstructionGotoTable(table_id=1)] # match = parser.OFPMatch(eth_type=ether_types.ETH_TYPE_MPLS, # ip_proto=self.DATA_PROTOCOL) # self.add_flow(datapath, 0, 3, match, None, instruction=ins) ## Send to controller if incoming packet is a registration one match = parser.OFPMatch(eth_dst = self.CONTROLLER_ETH, eth_type=ether_types.ETH_TYPE_MPLS) actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER, ofproto.OFPCML_NO_BUFFER)] self.add_flow(datapath, 0, 2, match, actions) else: print("insert initial rules in legacy switch "+str( datapath.id)) match = parser.OFPMatch() # Match everything actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER, ofproto.OFPCML_NO_BUFFER)] ''' Add a flow(role) with priority 0 (lowest priority) in order to send mismatched requests to the controller ''' self.add_flow(datapath, 0, 0, match, actions) self.add_flow(datapath, 1, 0, match, actions) ins = [parser.OFPInstructionGotoTable(table_id=1)] match = parser.OFPMatch() self.add_flow(datapath, 0, 1, match, None, instruction=ins) def add_flow(self, datapath, table_id, priority, match, actions, instruction=None): """ Add entry to switch table :param datapath: target switch :param table_id: id of table! :param priority: higher number means higher priority :param match: which flows match this entry :param actions: what to do for matched flow :param instruction: set for instruction commands such as GotoTable :return: null """ ofproto = datapath.ofproto parser = datapath.ofproto_parser if not instruction: inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS, actions)] mod = parser.OFPFlowMod(datapath=datapath, table_id=table_id, priority=priority, match=match, instructions=inst) elif not actions: mod = parser.OFPFlowMod(datapath=datapath, table_id=table_id, priority=priority, command=ofproto.OFPFC_ADD, match=match, instructions=instruction) else: action_list = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS, actions)] inst = action_list + instruction mod = parser.OFPFlowMod(datapath=datapath, table_id=table_id, priority=priority, command=ofproto.OFPFC_ADD, match=match, instructions=inst) datapath.send_msg(mod) def packet_decode(self,pkt): """ Decode a packet and create a dictionary of its fields :param pkt: target packet :return: if packet is a LLDP it returns None, otherwise it returns the dictionary of its fields """ fields = dict() ######################################## # Layer2 information of packet(Ethernet) eth = pkt.get_protocol(ethernet.ethernet) fields['eth_type'] = eth.ethertype # Ignore lldp(Link Layer Discovery Protocol) packet if fields['eth_type'] == ether_types.ETH_TYPE_LLDP: return None # ethernet src and dst of packet fields['eth_dst'] = eth.dst fields['eth_src'] = eth.src ############# # MPLS header mpls_header = pkt.get_protocol(mpls.mpls) if mpls_header: print ('mpls header') fields['mpls_label'] = mpls_header.label print (fields['mpls_label']) else: fields['mpls_label'] = -1 ip = pkt.get_protocol(ipv4.ipv4) if ip: print('ip payload:') fields['ip_src'] = ip.src fields['ip_dst'] = ip.dst fields['ip_protocol'] = ip.proto else: fields['ip_protocol'] = -1 return fields def lookup_out_port(self,msg_data_path, ip_src, content_label=None, ip_dst=None): if content_label is not None: print ('searching ', content_label) publisher = self.RIB.lookup(content_label) else: publisher = dict({'ip':ip_dst}) if publisher is not None and publisher['ip'] in self.net: print('lookup path for ' + str(publisher['ip']) + ' from ' + str(ip_src)) path = nx.shortest_path(self.net, ip_src, publisher['ip']) # for switch in path[1:]: #dpid = msg_data_path.id return publisher['ip'], path # next_hop = path[path.index(dpid)+1] # #dpid = next_hop # #datapath = api.get_datapath(self, dpid) # print ('forward to: ',out_port) # return [out_port,publisher['ip']] else: print ('flood') #out_port = msg_data_path.ofproto.OFPP_FLOOD #if pkt_fields['eth_dst'] != "ff:ff:ff:ff:ff:ff": #return [out_port,''] return '',msg_data_path.ofproto.OFPP_FLOOD def encode_flow_id(self, ip_src,ip_dst): fields_src=ip_src.split(".") fields_dst=ip_dst.split(".") return fields_src[3]+'.'+fields_src[2]+'.'+ fields_dst[3]+'.' + fields_dst[2] def lookup_flow_id_path(self, flow_id): return self.RIB.get_flow_path(flow_id) def create_mpls_datapath(self, msg, pkt_fields): """ Add a flow in table 1 for pop mpls header and set appropriate IP destination and then goto table2 In table 2 for interest packets, tos field is set to be the in_port and then interest and data packets goto table 3 In table 3 forwarding rules for interest or data packets are added :param msg: target incoming msg :param pkt_fields: the fields of incoming interest packet :param oport: the port to forward packet on if necessary :return: created packet_out """ msg_datapath = msg.datapath parser = msg_datapath.ofproto_parser iport = msg.match['in_port'] ip_dst, next_ports = self.lookup_out_port(msg_datapath, pkt_fields['ip_src'], content_label=pkt_fields['mpls_label']) if ip_dst=='': return flow_id = self.encode_flow_id(pkt_fields['ip_src'],ip_dst) print('path: ', flow_id, ': ', next_ports) #add a rule to remove mpls and set ip_desAddr to publisher ip if msg_datapath.id in self.icn_switches: ins = [parser.OFPInstructionGotoTable(table_id=2)] actions = [parser.OFPActionPopMpls(ethertype=2048), parser.OFPActionSetField(ipv4_dst=flow_id)] match = parser.OFPMatch(eth_type=ether_types.ETH_TYPE_MPLS, mpls_label=pkt_fields['mpls_label']) self.add_flow(msg_datapath, 1, 1, match, actions, instruction=ins) #send back the packet to the switch for matching operations #data = None # if msg.buffer_id == ofproto.OFP_NO_BUFFER: # print("data_mpls=msg.data") # data = msg.data actions.append(parser.OFPActionSetField(ip_dscp=iport)) actions.append(parser.OFPActionOutput(SH_IN_PORT)) #actions.append(parser.OFPActionOutput(oport)) out = parser.OFPPacketOut(datapath=msg_datapath, buffer_id=msg.buffer_id, in_port=iport, actions=actions) else: next_hop = next_ports[2] oport = self.net[msg_datapath.id][next_hop]['port'] ins = [parser.OFPInstructionGotoTable(table_id=1)] actions = [parser.OFPActionPopMpls(ethertype=2048), parser.OFPActionSetField(ipv4_dst=flow_id)] match = parser.OFPMatch(eth_type=ether_types.ETH_TYPE_MPLS, mpls_label=pkt_fields['mpls_label']) self.add_flow(msg_datapath, 0, 2, match, actions, instruction=ins) actions.append(parser.OFPActionOutput(oport)) out = parser.OFPPacketOut(datapath=msg_datapath, buffer_id=msg.buffer_id, in_port=iport, actions=actions) #config table 2 flows and defaut flows of table 3 to goto SH if self.RIB.add_flow(flow_id,iport, next_ports)==0: self.create_ndn_datapath(msg,pkt_fields,flow_id,next_ports) return out def create_ndn_datapath(self, msg, pkt_fields,flow_id, next_ports): msg_datapath = msg.datapath parser = msg_datapath.ofproto_parser iport = msg.match['in_port'] #add a rule to set ip_tos to in_port ss = next_ports.index(msg_datapath.id) for switch in next_ports[ss:len(next_ports)-1]: msg_datapath = self.switches_dp[switch] next_hop = next_ports[next_ports.index(switch)+1] oport = self.net[switch][next_hop]['port'] if switch in self.icn_switches: #print('add flow for switch ', switch) ins = [parser.OFPInstructionGotoTable(table_id=3)] actions = [parser.OFPActionSetField(ip_dscp=iport)] match = parser.OFPMatch(in_port=iport, eth_type=ether_types.ETH_TYPE_IP, ip_proto=self.INTEREST_PROTOCOL) self.add_flow(msg_datapath, 2, 2, match, actions, instruction=ins) match = parser.OFPMatch(in_port=oport, eth_type=ether_types.ETH_TYPE_IP, ip_proto=self.DATA_PROTOCOL) self.add_flow(msg_datapath, 2, 2, match, None, instruction=ins) # send interest packets to SH actions = [parser.OFPActionOutput(SH_IN_PORT)] #actions = [parser.OFPActionOutput(oport)] #print('add flow for table 3 in switch ', switch) match = parser.OFPMatch(in_port=iport,eth_type=ether_types.ETH_TYPE_IP, ip_proto=self.INTEREST_PROTOCOL) self.add_flow(msg_datapath, 3, 1, match, actions) # send data packets on backward path to the service host actions = [parser.OFPActionOutput(SH_IN_PORT)] #actions = [parser.OFPActionOutput(iport)] match = parser.OFPMatch(in_port=oport,eth_type=ether_types.ETH_TYPE_IP, ip_proto=self.DATA_PROTOCOL) self.add_flow(msg_datapath, 3, 2, match, actions) # Add Forward interest path to the destination actions = [parser.OFPActionOutput(oport)] match = parser.OFPMatch(in_port=SH_OUT_PORT, eth_type=ether_types.ETH_TYPE_IP, ip_proto=self.INTEREST_PROTOCOL, ipv4_dst=flow_id) #match = parser.OFPMatch(mpls_label=mpls_label, in_port=SH_PORT) self.add_flow(msg_datapath, 3, 3, match, actions) # Add backward data path to the source actions = [parser.OFPActionDecNwTtl(),parser.OFPActionOutput(iport)] match = parser.OFPMatch(in_port=SH_OUT_PORT, eth_type=ether_types.ETH_TYPE_IP, ip_proto=self.DATA_PROTOCOL, ip_dscp=iport) self.add_flow(msg_datapath, 3, 4, match, actions) else: print('Create channel for forwarding on virtual link in order to forward in non ICN switch') print('flow_id:', flow_id, ',switch:', switch, ',next_switch:',next_hop ,',in port: ', iport, 'oport:', oport) #for interests actions = [parser.OFPActionOutput(oport)] match = parser.OFPMatch(in_port=iport, eth_type=ether_types.ETH_TYPE_IP, ip_proto=self.INTEREST_PROTOCOL, ipv4_dst=flow_id) self.add_flow(msg_datapath, 1, 1, match, actions) #for data actions = [parser.OFPActionDecNwTtl(), parser.OFPActionOutput(iport)] match = parser.OFPMatch(in_port=oport, eth_type=ether_types.ETH_TYPE_IP, ip_proto=self.DATA_PROTOCOL, ipv4_dst=flow_id) self.add_flow(msg_datapath, 1, 1, match, actions) print('finding iport from next_hop '+str(next_hop)+ ' to switch ' + str(switch)) print(self.net[next_hop]) if 'port' in self.net[next_hop][switch]: iport = self.net[next_hop][switch]['port'] #send back the packet to the switch for matching operations oport = self.net[msg.datapath.id][next_ports[next_ports.index(msg.datapath.id)+1]]['port'] # data = None # if msg.buffer_id == ofproto.OFP_NO_BUFFER: # print("data_ndn=msg.data") # data = msg.data #actions = actions.append(parser.OFPActionOutput(SH_IN_PORT)) actions = [parser.OFPActionSetField(ip_dscp=iport), parser.OFPActionOutput(SH_IN_PORT)] out = parser.OFPPacketOut(datapath=msg.datapath, buffer_id=msg.buffer_id, in_port=iport, actions=actions) return out def create_legacy_datapath(self,msg, pkt_fields): """ forward any other packets except NDN packets :param msg: target incoming msg :param out_port: the port to forward packet on if necessary :return: created packet_out """ datapath = msg.datapath dpid = datapath.id ofproto = datapath.ofproto parser = datapath.ofproto_parser in_port = msg.match['in_port'] # Input port of switch (to the source) if pkt_fields['ip_dst'] in self.net: # print 'it is' path = nx.shortest_path(self.net, pkt_fields['ip_src'], pkt_fields['ip_dst']) # for switch in path[1:]: next_hop = path[path.index(dpid)+1] out_port = self.net[dpid][next_hop]['port'] else: out_port = ofproto.OFPP_FLOOD if pkt_fields['eth_dst'] != "ff:ff:ff:ff:ff:ff": return actions = [parser.OFPActionOutput(out_port, ofproto.OFPCML_NO_BUFFER)] match = parser.OFPMatch(eth_type=pkt_fields['eth_type'], ipv4_dst=pkt_fields['ip_dst']) self.add_flow(datapath, 0, 1, match, actions) data = None if msg.buffer_id == ofproto.OFP_NO_BUFFER: data = msg.data out = parser.OFPPacketOut(datapath=datapath, buffer_id=msg.buffer_id, in_port=in_port, actions=actions, data=data) return out @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER) def _packet_in_handler(self, ev): """ Packet_In event; Mismatched in switch and it asks controller :param ev: Event :return: """ msg = ev.msg datapath = msg.datapath dpid = datapath.id # Switch id in_port = msg.match['in_port'] pkt = packet.Packet(msg.data) pkt_fields = self.packet_decode(pkt) if pkt_fields is None or pkt_fields['ip_protocol']==-1: return self.packet_in_num += 1 # Add hosts to the net graph if pkt_fields['ip_src'] not in self.net: print ('add '+ pkt_fields['ip_src']) self.net.add_node(pkt_fields['ip_src']) self.net.add_edge(dpid, pkt_fields['ip_src'], port=in_port) self.net.add_edge(pkt_fields['ip_src'], dpid) # if pkt_fields['ip_protocol'] == self.REGISTER_PROTOCOL: if pkt_fields['mpls_label']==self.HELLO_LABEL: print('add switch %i as an ICN switch' %dpid) self.icn_switches.append(dpid) self.switch_features_handler(ev) else: print ('New data registration in %i' % dpid) self.RIB.add(pkt_fields['mpls_label'],pkt_fields['ip_src'],pkt_fields['eth_src']) return # install a flow(role) to avoid packet_in next time # Interest packets if pkt_fields['ip_protocol'] == self.INTEREST_PROTOCOL: # if dst_port == self.INTEREST_PORT: """ Interest packets has special ip_protocol number (150) If ip_protocol == 150 -> Interest packet """ print ('New interest in %i ' % dpid ) if (pkt_fields['mpls_label']>0): out = self.create_mpls_datapath(msg, pkt_fields) else: print('packet flow_id: ', pkt_fields['ip_dst']) path = self.lookup_flow_id_path(pkt_fields['ip_dst']) out = self.create_ndn_datapath(msg, pkt_fields,pkt_fields['ip_dst'],path) datapath.send_msg(out) elif pkt_fields['ip_protocol'] == self.DATA_PROTOCOL: """ Data packets has special ip_protocol number (151) If ip_protocol == 151 -> Data packet """ print ('New data in %i' % dpid) print ('in_port:',in_port) elif pkt_fields['ip_protocol'] != -1: """ Other packets forward normally based on SDN """ print ('Not NDN packet %i' % dpid) # self.logger.info("s%s from:%s to:%s sport:%s dport:%s", # dpid, et_src, et_dst, in_port, out_port) out = self.create_legacy_datapath(msg,pkt_fields) if out is not None: datapath.send_msg(out) @set_ev_cls(event.EventSwitchEnter) def get_topology_data(self, ev): s_id = ev.switch.dp.id print('-----------------------------------------------') print('new switch:',s_id) links_list = get_link(self,s_id) while(len(links_list)==0): links_list = get_link(self,s_id) links = [(link.src.dpid, link.dst.dpid, {'port': link.src.port_no}) for link in links_list] self.links.extend(links) links = [(link.dst.dpid, link.src.dpid, {'port': link.dst.port_no}) for link in links_list] self.links.extend(links) self.switches.append(s_id) print(self.links) self.net.add_nodes_from(self.switches) self.net.add_edges_from(self.links)
class Login(QWidget): def __init__(self): super().__init__() self.initialize_ui() def initialize_ui(self): self.setWindowTitle("Login GUI") self.setGeometry(100, 100, 400, 230) self.login_user_interface() self.show() def login_user_interface(self): """ Create the login GUI """ login_label = QLabel("login", self) login_label.move(180, 10) login_label.setFont(QFont('Arial', 20)) name_label = QLabel("username:"******"password:"******"show password", self) show_pass_cb.move(110, 115) show_pass_cb.stateChanged.connect(self.show_password) show_pass_cb.toggle() show_pass_cb.setChecked(False) not_a_member = QLabel("not a member?", self) not_a_member.move(70, 200) sign_up = QPushButton("sign up", self) sign_up.move(160, 195) sign_up.clicked.connect(self.create_new_user) def click_login(self): """ When user clicks sign in button, check username and password match any existing profiles in users.txt. If they exists, display error messagebox. """ users = {} # create empty dictionary to store user information # Check id users.txt exists, otherwise create new file try: with open("files/users.txt", "r") as f: for line in f: user_fields = line.split(" ") username = user_fields[0] password = user_fields[1].strip('\n') users[username] = password except FileNotFoundError: print("The file does not exists. Creating a new file.") open("files/users.txt", "w") username = self.name_entry.text() password = self.pass_entry.text() if (username, password) in users.items(): QMessageBox.information(self, "Login Successful!", "Login Successful!", QMessageBox.Ok, QMessageBox.Ok) self.close() else: QMessageBox.warning(self, "Error Message", "The username or password is incorrect.", QMessageBox.Cancel, QMessageBox.Cancel) def show_password(self, state): """ If checkbox is enabled, view password. Else, mask password so others cannot see it. :param state: state of the checkbox - True or False """ if state == Qt.Checked: self.pass_entry.setEchoMode(QLineEdit.Normal) else: self.pass_entry.setEchoMode(QLineEdit.Password) 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()
class Window(QMainWindow): def __init__(self): super().__init__() uic.loadUi("project.ui", self) # Подключение главного интерфейса self.picture.setPixmap(QPixmap("help.png")) # Подключение картинки к главному интерфейсу self.database = DataBase() self.refresh_database() # Берем данные из бд self.initUI() def initUI(self): self.reg.clicked.connect(self.registration) self.login_patients.clicked.connect(self.login_for_patients) self.login_doc.clicked.connect(self.login_for_doc) # Подключение кнопок к функциям def refresh_database(self): self.auth_doc = self.database.get_data("auth_doctors") self.doc = self.database.get_data("doctors") self.auth_patients = self.database.get_data("auth_patients") self.patients = self.database.get_data("patients") def registration(self): self.reg_patients = Registration() self.reg_patients.show() self.reg_patients.finish.clicked.connect(self.add_patients) self.reg_patients.exec() # Подключение интерфейса регистрации def add_patients(self): try: if self.reg_patients.surname.text() == "": self.reg_patients.error.resize(100, 16) self.reg_patients.error.setText("Введите фамилию!") self.reg_patients.error.setStyleSheet("color : red") return # Проверка поля "Фамилия" на наличие данных elif self.reg_patients.name.text() == "": self.reg_patients.error.resize(70, 16) self.reg_patients.error.setText("Введите имя!") self.reg_patients.error.setStyleSheet("color : red") return # Проверка поля "Имя" на наличие данных elif self.reg_patients.phone.text() == "": self.reg_patients.error.resize(100, 16) self.reg_patients.error.setText("Введите телефон!") self.reg_patients.error.setStyleSheet("color : red") return # Проверка поля "Телефон" на наличие данных check_phone(self.reg_patients.phone.text()) # Проверка поля "Телефон" на корректность данных if self.reg_patients.address.text() == "": self.reg_patients.error.resize(85, 16) self.reg_patients.error.setText("Введите адрес!") self.reg_patients.error.setStyleSheet("color : red") return # Проверка поля "Адрес" на наличие данных elif self.reg_patients.login.text() == "": self.reg_patients.error.resize(85, 16) self.reg_patients.error.setText("Введите логин!") self.reg_patients.error.setStyleSheet("color : red") return # Проверка поля "Логин" на наличие данных elif any([ self.reg_patients.login.text().strip() == str(i[1]) for i in self.auth_patients ]): self.reg_patients.error.resize(150, 16) self.reg_patients.error.setText("Такой логин уже занят!") self.reg_patients.error.setStyleSheet("color : red") return # Проверка данных поля "Логин" на совпадение в бд elif self.reg_patients.password.text() == "": self.reg_patients.error.resize(90, 16) self.reg_patients.error.setText("Введите пароль!") self.reg_patients.error.setStyleSheet("color : red") return # Проверка поля "Пароль" на наличие данных elif self.reg_patients.password2.text() == "": self.reg_patients.error.resize(150, 16) self.reg_patients.error.setText("Введите пароль повторно!") self.reg_patients.error.setStyleSheet("color : red") return # Проверка поля "Повторите пароль" на наличие данных check_password(self.reg_patients.password.text()) # Проверка поля "Пароль" на корректность данных if self.reg_patients.password.text() != \ self.reg_patients.password2.text(): self.reg_patients.error.resize(120, 16) self.reg_patients.error.setText("Пароли не совпадают!") self.reg_patients.error.setStyleSheet("color : red") # Сравнение поля "Пароль" и поля "Повторите пароль" else: date = list( self.reg_patients.birthdate.selectedDate().getDate()) date2 = " ".join(map(str, date)) # Дата рождения self.database.add_data("auth_patients(login, password)", (self.reg_patients.login.text(), self.reg_patients.password.text())) self.database.add_data( "patients(surname, name, patronymic," " gender, phone_number, address," " birthdate)", (self.reg_patients.name.text(), self.reg_patients.surname.text(), self.reg_patients.patronymic.text(), self.reg_patients.gender.currentText(), self.reg_patients.phone.text(), self.reg_patients.address.text(), date2)) self.refresh_database() # Добавление всех данных в бд self.reg_patients.close() # Закрытие интерфейса except Exception as exc: self.reg_patients.error.resize(len(str(exc)) * 6 - 5, 16) self.reg_patients.error.setText(str(exc)) self.reg_patients.error.setStyleSheet("color : red") # Отлавливаем ошибки def login_for_patients(self): self.login_patients = Login() self.login_patients.show() self.login_patients.ok.clicked.connect(self.check_patients) self.login_patients.exec() # Подключение интерфейса входа def check_patients(self): if self.login_patients.output_login.text() != "": # Проверка поля "Логин" на наличие данных for patients in self.auth_patients: id, login, password = patients if self.login_patients.output_login.text() == str(login): # Проверка поля "Логин" на корректность данных if self.login_patients.output_password.text() == \ str(password): self.login_patients.close() self.load_data_for_patients(id_patients=id) break elif self.login_patients.output_password.text() != "": self.login_patients.error.setText("Неверный " "пароль!!!") self.login_patients.error.setStyleSheet("color : red") break else: self.login_patients.error.setText("Введите пароль!!!") self.login_patients.error.setStyleSheet("color : red") break # Проверка поля "Пароль" на корректность данных else: self.login_patients.error.setText("Неверный логин!!!") self.login_patients.error.setStyleSheet("color : red") else: self.login_patients.error.setText("Введите логин!!!") self.login_patients.error.setStyleSheet("color : red") def load_data_for_patients(self, id_patients): patients = ChoiceWidget(id_patients) patients.show() patients.exec() # Загрузка интерфейса для пациента def login_for_doc(self): self.login_doc = Login() self.login_doc.show() self.login_doc.ok.clicked.connect(self.check_doc) self.login_doc.exec() # Подключение интерфейса входа def check_doc(self): if self.login_doc.output_login.text() != "": # Проверка поля "Логин" на наличие данных for doc in self.auth_doc: id, login, password = doc if self.login_doc.output_login.text() == str(login): # Проверка поля "Логин" на корректность данных if self.login_doc.output_password.text() == str(password): self.login_doc.close() self.load_data_for_doc(id_doc=id) break elif self.login_doc.output_password.text() != "": self.login_doc.error.setText("Неверный пароль!!!") self.login_doc.error.setStyleSheet("color : red") break else: self.login_doc.error.setText("Введите пароль!!!") self.login_doc.error.setStyleSheet("color : red") break # Проверка поля "Пароль" на корректность данных else: self.login_doc.error.setText("Неверный логин!!!") self.login_doc.error.setStyleSheet("color : red") else: self.login_doc.error.setText("Введите логин!!!") self.login_doc.error.setStyleSheet("color : red") def load_data_for_doc(self, id_doc): doc = DocWidget(id_doc) doc.show() doc.exec()
from registration import Registration reg = Registration() email = input('Input email: ') password = input('Input password: ') reg.register(email, password)
def fee(self): size = self.business.nr_employees num_subteams = self.business.num_subteams registration_date = self.applied return Registration.fee(size, num_subteams, registration_date)
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)