def msg_handler(self, breakMessage, address): ''' This handles the message sending request from the client ''' global CLIENTDATA #Check if the message does not contain a character on <numberOfClients> part if not breakMessage[3].isdigit(): self.send(address, "err_unknown_message", 2) print("disconnected:", util.get_key(CLIENTDATA, address)) #Check if the number of usernames enters is not less than specified in the message elif len(breakMessage) - 4 <= int(breakMessage[3]): self.send(address, "err_unknown_message", 2) print("disconnected:", util.get_key(CLIENTDATA, address)) #If no format error else: print("msg:", util.get_key(CLIENTDATA, address)) end = int(breakMessage[3]) + 4 #Traverse through the usernames to which client wants to send the message to senderName = util.get_key(CLIENTDATA, address) for i in range(4, end): #The destination username exits if CLIENTDATA.get(breakMessage[i]) is not None: message = senderName + ": " + " ".join(breakMessage[end:]) destinationAddress = ((CLIENTDATA.get(breakMessage[i]))[0], (CLIENTDATA.get(breakMessage[i]))[1]) self.send(destinationAddress, "forward_message", 4, message) #The destination username does not exits else: print("msg:", util.get_key(CLIENTDATA, address), "to non-existent user", breakMessage[i])
def present_result(self, games, ICM_link): print(self.tags) time = datetime.now() folder = time.strftime("%d_%m_%Y_%H_%M_%S") path = os.getcwd() destination_path = path.replace("code", "") + "outputs\\" + folder os.makedirs(destination_path) for i in range(4): game = games[i] name = util.get_key(self.itemID_to_index, game) link = ICM_link[ICM_link["name"] == name]["link"].iloc[0] website = requests.get(link).content soup = BeautifulSoup(website, 'html.parser') try: elem = str( list( soup.findAll("div", { "class": "game_header_image_ctn" }).pop().children)[1]) img_link = elem.replace( "<img class=\"game_header_image_full\" src=\"", "").replace("\"/>", "") response = requests.get(img_link) img = Image.open(BytesIO(response.content)) img.convert('RGB').save("..\\outputs\\" + folder + "\\" + cleanup_name(name) + "_a.png", "PNG", optimize=True) except IndexError: print("Error") recommended_tags = self.ICM[self.ICM["ItemID"] == game]["FeatureID"].values recommended_tags_ID = [] for r in recommended_tags: recommended_tags_ID.append( util.get_key(self.featureID_to_index, r)) print() print(name) print(recommended_tags_ID) if i >= 2: self.show_wordcloud(folder, game, recommended_tags_ID) print(link)
def unknown_handler(self, breakMessage, address): ''' This handles the unknown request from the client ''' global CLIENTDATA global CLIENTUSERNAME global CLIENTCONNECTED #Disconnect the client and remove the username from the client data print("disconnected:", util.get_key(CLIENTDATA, address), "sent unknown command") self.send(address, "err_unknown_message", 2) deleteUsername = util.get_key(CLIENTDATA, address) CLIENTUSERNAME.remove(deleteUsername) del CLIENTDATA[deleteUsername] CLIENTCONNECTED -= 1
def post(self): """Post short URL. Returns a short URL for a long URL. :param object request_body: contains the short and long URL :rtype: json: contains the short, long URL and a bool, if the combination is valid or not """ body = request.get_json() short_url = body["short_url"] long_url = body["long_url"] custom_salt = get_key(body, 'custom_salt') url_manager = UrlManager() valid = url_manager.validate_url(short_url="/" + short_url, long_url=long_url, custom_salt=custom_salt) message = { 'short_url': short_url, 'long_url': long_url, 'valid': valid } status = 200 response = app.response_class(response=json.dumps(message), status=status, mimetype='application/json') return response
def on_status(self, status): key = util.get_key(status.text) + '-text' prev_status = self.cache.get(key) if (status.user.screen_name not in self.filter_config['excluded_accounts'] and not prev_status and any(word in status.text for word in self.filter_config['keywords']) and not any(word in status.text for word in self.filter_config['excluded_keywords'])): self.cache.set(key, status) self.tweet_num += 1 logger.log(' '.join([ 'scheduling tweet_id', str(status.id), 'from', status.user.screen_name, 'matching', ','.join([ word for word in self.filter_config['keywords'] if word in status.text ]), 'as tweet_num:', str(self.tweet_num) ])) self.channel.basic_publish( exchange='', routing_key=self.rabbitmq_config['queue'], body=pickle.dumps((self.tweet_num, status)), properties=pika.BasicProperties(delivery_mode=2)) sys.stdout.flush()
def post(self): """Post short URL. Returns a short URL for a long URL. :param object request_body: the long URL with its meta data :rtype: json: contains the long URL, the short URL and the metadata """ body = request.get_json() long_url = body["long_url"] custom_salt = get_key(body, 'custom_salt') custom_url = get_key(body, 'custom_url') tag = get_key(body, 'tag') metadata = get_key(body, 'metadata') url_type = body["type"][0] if url_type == 'iota': url = IotaUrl(address=long_url, tag=tag, metadata=metadata, custom_salt=custom_salt) elif url_type == 'document': url = DocumentUrl(document_hash=long_url, tag=tag, metadata=metadata, custom_salt=custom_salt) else: url = Url(long_url=long_url, tag=tag, metadata=metadata, custom_salt=custom_salt) if custom_url: url.random_id = custom_url url_manager = UrlManager() message = url_manager.publish_url(url=url) message = message.json status = 200 response = app.response_class(response=json.dumps(message), status=status, mimetype='application/json') return response
def list_handler(self, breakMessage, address): ''' This handles the list message from the client ''' global CLIENTUSERNAME print("request_users_list:", util.get_key(CLIENTDATA, address)) listCompile = "" #Traverse the client username list for username in CLIENTUSERNAME: listCompile += username + " " self.send(address, "response_users_list", 3, listCompile)
def smart_move(source, destination): result = urllib.parse.urlparse(destination) if result.scheme in ['', 'file']: with smart_open.smart_open(source, 'rb') as src: with smart_open.smart_open(destination, 'wb') as dst: shutil.copyfileobj(src, dst) elif result.scheme == 's3': get_s3client_for_bucket(destination).upload_file(source, get_bucket(result), get_key(result), Callback=ProgressPercentage(smart_size(source), source)) os.remove(source)
def key_exchange(n1, n2, id1, id2): kp1 = os.path.join(secret.key_path, id1) kp2 = os.path.join(secret.key_path, id2) if not os.path.exists(kp1) or not os.path.exists(kp2): print('User not found') exit(-1) kE1, kM1 = util.get_key(kp1) kE2, kM2 = util.get_key(kp2) shareKey = hexlify(get_random_bytes(32)) c2 = util.encrypt(kE2, shareKey) d2 = f'{id1}||{n1}||{n2}' t2 = util.mac(kM2, d2.encode()) c1 = util.encrypt(kE1, shareKey) d1 = f'{id2}||{n1}||{n2}' t1 = util.mac(kM1, d1.encode()) return c1, t1, c2, t2
def post(self): """ Retrieves the last requested short URLs :param object request_body: contains the different parameters: tag, number of entries, valid entries only :rtype: json: contains the requested short URL entries, retrieved from the tangle """ body = request.get_json() tag = get_key(body, 'tag') number = body["number"] if "number" in body else 5 valid_only = get_key(body, 'valid_only') url_manager = UrlManager() message = url_manager.last_urls(tag=tag, number=number, valid_only=valid_only) status = 200 response = app.response_class(response=json.dumps(message), status=status, mimetype='application/json') return response
def disconnect_handler(self, breakMessage, address): ''' This will handle the disconnection request from the client ''' global CLIENTDATA global CLIENTUSERNAME global CLIENTCONNECTED #Disconnect the client and delete the username from the server data print("disconnected:", breakMessage[2]) deleteUsername = util.get_key(CLIENTDATA, address) CLIENTUSERNAME.remove(deleteUsername) del CLIENTDATA[deleteUsername] CLIENTCONNECTED -= 1
def show_wordcloud(self, folder, game, recommended_tags_ID): file_content = ' '.join(recommended_tags_ID) wordcloud = WordCloud(stopwords=STOPWORDS, background_color='white', width=1200, height=1000, color_func=self.color).generate(file_content) name = util.get_key(self.itemID_to_index, game) plt.title(name, fontdict={'fontsize': 20}) plt.imshow(wordcloud) plt.axis('off') #plt.show() plt.savefig("..\\outputs\\" + folder + "\\" + cleanup_name(name) + "_b.png")
def update_pincode_maps_info(pincode): params = {'types': 'place', 'country': 'IN', 'worldview': 'in'} query = get_address_by_pincode(pincode) url = f"https://api.mapbox.com/geocoding/v5/mapbox.places/{query}.json?access_token={token}" response = requests.get(url, params) if response.status_code == 200: data = json.loads(response.content.decode()) features = get_key(data, ['features']) if len(features) > 0: feature_max_relevance = max(features, key=lambda x: x['relevance']) ret = dbHelper.update_pincode_info_set( pincode, {'mapboxFeatures': json.dumps(feature_max_relevance)}) if ret > 0: logger.log(DEBUG, f'Failed to update for pincode [{pincode}].')
def recommend(self, user_id, exclude_seen=True): user_profile = self.URM[user_id] scores = user_profile.dot(self.W_sparse).toarray().ravel() #print(scores) if exclude_seen: scores = self.filter_seen(user_id, scores) ranking = scores.argsort()[::-1] #print(ranking) recommended_items = 0 recommendations = [] for recommended in ranking: name = util.get_key(self.itemID_to_index, recommended) link = self.ICM_link[self.ICM_link["name"] == name]["link"].iloc[0] website = requests.get(link).content soup = BeautifulSoup(website, 'html.parser') dlc = False tags = soup.findAll("div", {"class": "game_area_details_specs"}) for t in tags: if "https://steamstore-a.akamaihd.net/public/images/v6/ico/ico_dlc.png" in str( t): dlc = True if not dlc: print("Recommended game: " + str(name)) already_known = input( "Do you already know this game? y or n: ") while already_known not in ["y", "n"]: already_known = input( "Do you already know this game? y or n: ") if already_known == "y": print("Suggesting a new one...") print() else: recommended_items += 1 recommendations.append(recommended) if recommended_items == 4: break return recommendations
def admin(name): kp = os.path.join(secret.key_path, name) if not os.path.exists(kp): print('User not found') exit(-1) kE, kM = util.get_key(kp) nonce = bytes_to_long(get_random_bytes(16)) print(f'Nonce: {nonce}') ticket = input('Ticket: ').strip() data = f'{name}||{nonce}' if ticket != util.mac(kM, data.encode()): print('Unauthorized') exit(-1) if name == 'Admin': return util.encrypt(kE, secret.FLAG2) else: msg = f'Hello guest, {name}' return util.encrypt(kE, msg.encode())
def handle_input(self): raw_key = tcod.console_check_for_keypress( tcod.KEY_PRESSED | tcod.KEY_RELEASED) while raw_key.vk != tcod.KEY_NONE: key = util.get_key(raw_key) if key == tcod.KEY_ESCAPE: self.alive = False for player in self.players: if player.controls not in ['ai', None]: if key in player.controls: if raw_key.pressed: if player.controls.index(key) == 0: # up player.up = True else: player.down = True # down else: if player.controls.index(key) == 0: # up player.up = False else: player.down = False raw_key = tcod.console_check_for_keypress( tcod.KEY_PRESSED | tcod.KEY_RELEASED)
def __init__(self, name, kp): self.name = name self.kE, self.kM = util.get_key(kp)
def __init__(self): super(AESBase, self).__init__() self.key = get_key(32) self.IV = get_iv(AES.block_size)
def start(self): ''' Main loop. continue receiving messages from Clients and processing it ''' clientUsername = [] #Will store the usernames of the clients clientData = { } #Will store the address of the clients with usernames as the key usernameExists = False #Boolian variable to check if the username is already taken or not clientConnected = 0 #Variable to track the number of clients connected sendMessage = "" #The message that will be made sendPacket = "" #The packer that will be send #Main loop while True: #Recieve the message, parse it and break into list revieveMessage, address = self.sock.recvfrom(4096) _, _, breakMessage, _ = util.parse_packet( revieveMessage.decode("utf-8")) breakMessage = breakMessage.split() #Check if the client has sent the join message if breakMessage[0].strip() == "join": #Check if the maximum client limit has been reached if clientConnected == util.MAX_NUM_CLIENTS: self.send(address, "err_server_full", 2) print("disconnected: server full") #If the client limit has not been reached else: #Traverse the client username list to check if the username is already taken for username in clientUsername: #If the username already exits if breakMessage[2].strip() == username.strip(): self.send(address, "err_server_full", 2) usernameExists = True print("disconnected: username not available") break #If the username does not exist if not usernameExists: clientUsername.append(breakMessage[2]) clientUsername.sort(key=str.casefold) clientData[breakMessage[2]] = address clientConnected += 1 print("join:", breakMessage[2]) usernameExists = False #Check if the client has requested the active users list elif breakMessage[0].strip() == "request_users_list": print("request_users_list:", util.get_key(clientData, address)) listCompile = "" #Traverse the client username list for username in clientUsername: listCompile += username + " " self.send(address, "response_users_list", 3, listCompile) #Check if the client wants to send the message elif breakMessage[0].strip() == "send_message": #Check if the message does not contain a character on <numberOfClients> part if not breakMessage[3].isdigit(): self.send(address, "err_unknown_message", 2) print("disconnected:", util.get_key(clientData, address)) #Check if the number of usernames enters is not less than specified in the message elif len(breakMessage) - 4 <= int(breakMessage[3]): self.send(address, "err_unknown_message", 2) print("disconnected:", util.get_key(clientData, address)) #If no format error else: print("msg:", util.get_key(clientData, address)) end = int(breakMessage[3]) + 4 #Traverse through the usernames to which client wants to send the message to for i in range(4, end): #The destination username exits if clientData.get(breakMessage[i]) is not None: message = util.get_key(clientData, address) + ": " + " ".join( breakMessage[end:]) destinationAddress = ((clientData.get( breakMessage[i]))[0], (clientData.get( breakMessage[i]))[1]) self.send(destinationAddress, "forward_message", 4, message) #The destination username does not exits else: print("msg:", util.get_key(clientData, address), "to non-existent user", breakMessage[i]) #Check if the client wants to send a file elif breakMessage[0].strip() == "send_file": #Check if the message does not contain a character on <numberOfClients> part if not breakMessage[3].isdigit(): self.send(address, "err_unknown_message", 2) print("disconnected:", util.get_key(clientData, address)) #If there is no format error else: print("file:", util.get_key(clientData, address)) end = int(breakMessage[3]) + 4 #Traverse through the usernames to which client wants to send the message to for i in range(4, end): #The destination username exits if clientData.get(breakMessage[i]) is not None: message = util.get_key(clientData, address) + " " + " ".join( breakMessage[end:]) destinationAddress = ((clientData.get( breakMessage[i]))[0], (clientData.get( breakMessage[i]))[1]) self.send(destinationAddress, "forward_file", 4, message) #The destination username does not exits else: print("file:", util.get_key(clientData, address), "to non-existent user", breakMessage[i]) #Check if the client wants to disconnet elif breakMessage[0].strip() == "disconnect": clientUsername.remove(breakMessage[2]) clientData.pop(breakMessage[2]) clientConnected -= 1 print("disconnected:", breakMessage[2]) #If the format recieved is something unknown else: print("disconnected:", util.get_key(clientData, address), "sent unknown command") self.send(address, "err_unknown_message", 2)
def __init__(self): super(TripleDESBase, self).__init__() self.key = get_key(16) self.IV = get_iv(DES3.block_size)
def __init__(self): super(RC4Base, self).__init__() self.key = get_key(16)
def smart_etag(url) -> str: result = urllib.parse.urlparse(url) if result.scheme in ['', 'file']: return os.path.getmtime(url) elif result.scheme == 's3': try: response = get_s3client_for_bucket(url).head_object(Bucket=get_bucket(result), Key=get_key(result)) size = response['ETag'][1:-1] return size > 0 except Exception as e: return False
def process_mail_dic(mail): mail_id = mail['id'] sender = None subject = None text = None unsubscribe_option = None files = [] for part in mail['payloads']: for header in part.get('headers', []): header_name = header['name'].lower() header_value = header['value'] # Get sender email if header_name == 'from': sender = header_value.split(' ')[-1].strip('<>') elif header_name == 'subject': subject = header_value elif header_name == 'list-unsubscribe': unsubscribe_option = header_value mime_type = get_key(part, ['mimeType']) data = get_key(part, ['body', 'data']) filename = get_key(part, ['filename'], '') if len(filename) > 0: files.append(filename) continue if data is None: continue data = base64.urlsafe_b64decode(data).decode() if 'html' in mime_type: # prefer text from html over text from html soup = BeautifulSoup(data, 'lxml') text = soup.text # double check in html content to see if something's found if unsubscribe_option is None: checklist = ['opt-out', 'unsubscribe', 'edit your notification settings'] for link in soup.find_all('a', href=True): link_text = link.text.strip().lower() if any(item in link_text for item in checklist): unsubscribe_option = link['href'] break elif mime_type == 'text/plain': if text is None: text = data else: print(f'Unseen mime-type found [{mime_type}].') processed_data = { 'Id': str(mail_id), 'Sender': sender, 'Subject': subject, 'Text': text, 'Unsubscribe': unsubscribe_option, 'Files': files, } return processed_data
def smart_delete(url): result = urllib.parse.urlparse(url) if result.scheme in ['', 'file']: return os.remove(url) elif result.scheme == 's3': response = get_s3client_for_bucket(url).delete_object(Bucket=get_bucket(result), Key=get_key(result))
def smart_size(url): result = urllib.parse.urlparse(url) if result.scheme in ['', 'file']: return os.path.getsize(url) elif result.scheme == 's3': try: response = get_s3client_for_bucket(url).head_object(Bucket=get_bucket(result), Key=get_key(result)) size = response['ContentLength'] return size > 0 except Exception as e: return False
def test_MirrorSessionAddModifyAndDelete(self, dvs, testlog): # Initialize database connectors self._set_up(dvs) # Maintain list of original Application and ASIC DB entries before adding # new mirror session original_appl_mirror_entries = util.get_keys( self._p4rt_mirror_session_wrapper.appl_db, self._p4rt_mirror_session_wrapper.APP_DB_TBL_NAME + ":" + self._p4rt_mirror_session_wrapper.TBL_NAME) original_appl_state_mirror_entries = util.get_keys( self._p4rt_mirror_session_wrapper.appl_state_db, self._p4rt_mirror_session_wrapper.APP_DB_TBL_NAME + ":" + self._p4rt_mirror_session_wrapper.TBL_NAME) original_asic_mirror_entries = util.get_keys( self._p4rt_mirror_session_wrapper.asic_db, self._p4rt_mirror_session_wrapper.ASIC_DB_TBL_NAME) # 1. Create mirror session mirror_session_id = "mirror_session1" action = "mirror_as_ipv4_erspan" port = "Ethernet8" src_ip = "10.206.196.31" dst_ip = "172.20.0.203" src_mac = "00:02:03:04:05:06" dst_mac = "00:1A:11:17:5F:80" ttl = "0x40" tos = "0x00" attr_list_in_app_db = [ (self._p4rt_mirror_session_wrapper.ACTION, action), (util.prepend_param_field(self._p4rt_mirror_session_wrapper.PORT), port), (util.prepend_param_field( self._p4rt_mirror_session_wrapper.SRC_IP), src_ip), (util.prepend_param_field( self._p4rt_mirror_session_wrapper.DST_IP), dst_ip), (util.prepend_param_field( self._p4rt_mirror_session_wrapper.SRC_MAC), src_mac), (util.prepend_param_field( self._p4rt_mirror_session_wrapper.DST_MAC), dst_mac), (util.prepend_param_field(self._p4rt_mirror_session_wrapper.TTL), ttl), (util.prepend_param_field(self._p4rt_mirror_session_wrapper.TOS), tos) ] mirror_session_key = self._p4rt_mirror_session_wrapper.generate_app_db_key( mirror_session_id) self._p4rt_mirror_session_wrapper.set_app_db_entry( mirror_session_key, attr_list_in_app_db) util.verify_response(self._response_consumer, mirror_session_key, attr_list_in_app_db, "SWSS_RC_SUCCESS") # Query application database for mirror entries appl_mirror_entries = util.get_keys( self._p4rt_mirror_session_wrapper.appl_db, self._p4rt_mirror_session_wrapper.APP_DB_TBL_NAME + ":" + self._p4rt_mirror_session_wrapper.TBL_NAME) assert len( appl_mirror_entries) == len(original_appl_mirror_entries) + 1 # Query application database for newly created mirror key (status, fvs) = util.get_key(self._p4rt_mirror_session_wrapper.appl_db, self._p4rt_mirror_session_wrapper.APP_DB_TBL_NAME, mirror_session_key) assert status == True util.verify_attr(fvs, attr_list_in_app_db) # Query application state database for mirror entries appl_state_mirror_entries = util.get_keys( self._p4rt_mirror_session_wrapper.appl_state_db, self._p4rt_mirror_session_wrapper.APP_DB_TBL_NAME + ":" + self._p4rt_mirror_session_wrapper.TBL_NAME) assert len(appl_state_mirror_entries ) == len(original_appl_state_mirror_entries) + 1 # Query application state database for newly created mirror key (status, fvs) = util.get_key(self._p4rt_mirror_session_wrapper.appl_state_db, self._p4rt_mirror_session_wrapper.APP_DB_TBL_NAME, mirror_session_key) assert status == True util.verify_attr(fvs, attr_list_in_app_db) # Query ASIC database for mirror entries asic_mirror_entries = util.get_keys( self._p4rt_mirror_session_wrapper.asic_db, self._p4rt_mirror_session_wrapper.ASIC_DB_TBL_NAME) assert len( asic_mirror_entries) == len(original_asic_mirror_entries) + 1 # Query ASIC database for newly created mirror key asic_db_key = None for key in asic_mirror_entries: # Get newly created entry if key not in original_asic_mirror_entries: asic_db_key = key break assert asic_db_key is not None (status, fvs) = util.get_key( self._p4rt_mirror_session_wrapper.asic_db, self._p4rt_mirror_session_wrapper.ASIC_DB_TBL_NAME, asic_db_key) assert status == True # Get oid of Ethernet8 port_oid = util.get_port_oid_by_name(dvs, port) assert port_oid != None expected_attr_list_in_asic_db = [ (self._p4rt_mirror_session_wrapper. SAI_MIRROR_SESSION_ATTR_MONITOR_PORT, port_oid), (self._p4rt_mirror_session_wrapper.SAI_MIRROR_SESSION_ATTR_TYPE, "SAI_MIRROR_SESSION_TYPE_ENHANCED_REMOTE"), (self._p4rt_mirror_session_wrapper. SAI_MIRROR_SESSION_ATTR_ERSPAN_ENCAPSULATION_TYPE, "SAI_ERSPAN_ENCAPSULATION_TYPE_MIRROR_L3_GRE_TUNNEL"), (self._p4rt_mirror_session_wrapper. SAI_MIRROR_SESSION_ATTR_IPHDR_VERSION, "4"), # MIRROR_SESSION_DEFAULT_IP_HDR_VER (self._p4rt_mirror_session_wrapper.SAI_MIRROR_SESSION_ATTR_TOS, "0"), (self._p4rt_mirror_session_wrapper.SAI_MIRROR_SESSION_ATTR_TTL, "64"), (self._p4rt_mirror_session_wrapper. SAI_MIRROR_SESSION_ATTR_SRC_IP_ADDRESS, src_ip), (self._p4rt_mirror_session_wrapper. SAI_MIRROR_SESSION_ATTR_DST_IP_ADDRESS, dst_ip), (self._p4rt_mirror_session_wrapper. SAI_MIRROR_SESSION_ATTR_SRC_MAC_ADDRESS, src_mac), (self._p4rt_mirror_session_wrapper. SAI_MIRROR_SESSION_ATTR_DST_MAC_ADDRESS, dst_mac), (self._p4rt_mirror_session_wrapper. SAI_MIRROR_SESSION_ATTR_GRE_PROTOCOL_TYPE, "35006" ) # GRE_PROTOCOL_ERSPAN 0x88be ] util.verify_attr(fvs, expected_attr_list_in_asic_db) # 2. Modify the existing mirror session. new_dst_mac = "00:1A:11:17:5F:FF" attr_list_in_app_db[5] = (util.prepend_param_field( self._p4rt_mirror_session_wrapper.DST_MAC), new_dst_mac) self._p4rt_mirror_session_wrapper.set_app_db_entry( mirror_session_key, attr_list_in_app_db) util.verify_response(self._response_consumer, mirror_session_key, attr_list_in_app_db, "SWSS_RC_SUCCESS") # Query application database for the modified mirror key (status, fvs) = util.get_key(self._p4rt_mirror_session_wrapper.appl_db, self._p4rt_mirror_session_wrapper.APP_DB_TBL_NAME, mirror_session_key) assert status == True util.verify_attr(fvs, attr_list_in_app_db) # Query application state database for the modified mirror key (status, fvs) = util.get_key(self._p4rt_mirror_session_wrapper.appl_state_db, self._p4rt_mirror_session_wrapper.APP_DB_TBL_NAME, mirror_session_key) assert status == True util.verify_attr(fvs, attr_list_in_app_db) # Query ASIC DB about the modified mirror session. expected_attr_list_in_asic_db[9] = ( self._p4rt_mirror_session_wrapper. SAI_MIRROR_SESSION_ATTR_DST_MAC_ADDRESS, new_dst_mac) (status, fvs) = util.get_key( self._p4rt_mirror_session_wrapper.asic_db, self._p4rt_mirror_session_wrapper.ASIC_DB_TBL_NAME, asic_db_key) assert status == True util.verify_attr(fvs, expected_attr_list_in_asic_db) # 3. Delete the mirror session. self._p4rt_mirror_session_wrapper.remove_app_db_entry( mirror_session_key) util.verify_response(self._response_consumer, mirror_session_key, [], "SWSS_RC_SUCCESS") # Query application database for mirror entries appl_mirror_entries = util.get_keys( self._p4rt_mirror_session_wrapper.appl_db, self._p4rt_mirror_session_wrapper.APP_DB_TBL_NAME + ":" + self._p4rt_mirror_session_wrapper.TBL_NAME) assert len(appl_mirror_entries) == len(original_appl_mirror_entries) # Query application database for the deleted mirror key (status, fvs) = util.get_key(self._p4rt_mirror_session_wrapper.appl_db, self._p4rt_mirror_session_wrapper.APP_DB_TBL_NAME, mirror_session_key) assert status == False # Query application state database for mirror entries appl_state_mirror_entries = util.get_keys( self._p4rt_mirror_session_wrapper.appl_state_db, self._p4rt_mirror_session_wrapper.APP_DB_TBL_NAME + ":" + self._p4rt_mirror_session_wrapper.TBL_NAME) assert len(appl_state_mirror_entries) == len( original_appl_state_mirror_entries) # Query application state database for the deleted mirror key (status, fvs) = util.get_key(self._p4rt_mirror_session_wrapper.appl_state_db, self._p4rt_mirror_session_wrapper.APP_DB_TBL_NAME, mirror_session_key) assert status == False # Query ASIC database for mirror entries asic_mirror_entries = util.get_keys( self._p4rt_mirror_session_wrapper.asic_db, self._p4rt_mirror_session_wrapper.ASIC_DB_TBL_NAME) assert len(asic_mirror_entries) == len(original_asic_mirror_entries) # Query ASIC state database for the deleted mirror key (status, fvs) = util.get_key( self._p4rt_mirror_session_wrapper.asic_db, self._p4rt_mirror_session_wrapper.ASIC_DB_TBL_NAME, asic_db_key) assert status == False
def handle_main_menu(): tcod.console_init_root(SCREEN_WIDTH, SCREEN_HEIGHT, GAME_TITLE, False) # the player controls to send to the Game class # 'ai' = controlled by an ai player_controls = [controls[0], 'ai', ] conway_speed = CONWAY_SPEED map_width, map_height = CONWAY_SIZE max_fps = MAX_FPS color = False paddle_size = PADDLE_SIZE seamless = True while not tcod.console_is_window_closed(): tcod.console_clear(0) tcod.console_set_default_foreground(0, tcod.white) tcod.console_set_alignment(0, tcod.CENTER) tcod.console_print(0, SCREEN_WIDTH / 2, 2, 'Conway\'s Game of Pong') tcod.console_set_default_foreground(0, tcod.grey) tcod.console_print(0, SCREEN_WIDTH / 2, 3, 'by Spferical ([email protected])') tcod.console_print(0, SCREEN_WIDTH / 2, 4, 'Version %s' % VERSION) tcod.console_set_default_foreground(0, tcod.white) tcod.console_set_alignment(0, tcod.LEFT) tcod.console_print(0, 2, 6, '(a) Play') tcod.console_print(0, 2, 7, '(b) Exit') player_keys = ['c', 'd'] y = 8 x = 2 playernum = -1 for c in player_controls: y += 1 playernum += 1 k = player_keys[playernum] if c: tcod.console_set_default_foreground( 0, PLAYER_COLORS[playernum]) else: tcod.console_set_default_foreground(0, tcod.grey) if c and not c == 'ai': if c == [tcod.KEY_UP, tcod.KEY_DOWN]: str_controls = '[arrow keys]' else: str_controls = str(c) text = '(' + k + ') ' + str(playernum + 1) + ' Player ' + str_controls elif c == 'ai': text = '(' + k + ') ' + str(playernum + 1) + ' CPU' else: text = '(' + k + ') ' + str(playernum + 1) + ' Not Playing' tcod.console_print(0, x, y, text) tcod.console_set_default_foreground(0, tcod.white) tcod.console_print(0, 2, 13, '(e) Paddle size: ' + str(paddle_size)) tcod.console_print(0, 2, 14, '(f) Conway speed: ' + str(conway_speed)) tcod.console_print(0, 2, 16, '(g) Map width: ' + str(map_width)) tcod.console_print(0, 2, 17, '(h) Map height: ' + str(map_height)) tcod.console_print(0, 2, 19, '(i) FPS: ' + str(max_fps)) tcod.console_print(0, 2, 20, '(j) Fancy color effect (laggy): ' + \ str(color)) tcod.console_print(0, 2, 21, '(k) Game reset after every score: ' + \ str(not seamless)) tcod.console_flush() raw_key = tcod.console_check_for_keypress(tcod.KEY_PRESSED) key = util.get_key(raw_key) if key == 'a': g = game.Game(player_controls, conway_speed, (map_width, map_height), max_fps, color, paddle_size, seamless) g.run() #to clean up after Game tcod.console_init_root(SCREEN_WIDTH, SCREEN_HEIGHT, GAME_TITLE, False) elif key == 'b': break elif key in player_keys: p = player_keys.index(key) c = player_controls[p] if not c: player_controls[p] = controls[p] elif c == 'ai': player_controls[p] = None else: player_controls[p] = 'ai' elif key == 'e': paddle_size = whole_number_menu( paddle_size, 'The paddles will be how many blocks big?') elif key == 'f': conway_speed = whole_number_menu( conway_speed, 'The Life simulation will update every how many frames?') elif key == 'g': map_width = whole_number_menu( map_width, 'How wide should the map be?', min_var=1) elif key == 'h': map_height = whole_number_menu( map_height, 'How tall should the map be?', min_var=1) elif key == 'i': max_fps = whole_number_menu( max_fps, 'How many frames per second should the game ' + \ 'run at?\n (0 = no limit)') elif key == 'j': color = not color elif key == 'k': seamless = not seamless elif key == tcod.KEY_ESCAPE: break
def check_slots_available(pincode_info, pincode, age): logger.log(INFO, f'Check slots for pincode [{pincode}].') pincode_data = get_key(pincode_info, ['meta']) latest_timestamp = get_key(pincode_info, ['modifiedTime'], datetime.fromtimestamp(0)) curr_time = datetime.utcnow() time_diff = curr_time - latest_timestamp is_data_within_one_day = time_diff.total_seconds() < 24 * 3600 logger.log( DEBUG, f'For pincode [{pincode}], data exists: ' f'[{pincode_data is not None}], is data recent: [{is_data_within_one_day}].' ) slots_data = {} # if date available for this pincode is too old, discard it if pincode_data is not None and is_data_within_one_day: pincode_data = json.loads(pincode_data) for center in pincode_data['centers']: name = center['name'] address = center['address'] state = center['state_name'] district = center['district_name'] block = center['block_name'] pin_code_in_data = center['pincode'] lat = center['lat'] long = center['long'] from_time = center['from'] to_time = center['to'] fee_type = center['fee_type'] for session in center['sessions']: date = session['date'] min_age = session['min_age_limit'] capacity = session['available_capacity'] vaccine = session['vaccine'] slots = session['slots'] if min_age <= age and capacity > min_capacity: center_data = slots_data.get(name, {}) slots_data[name] = { 'name': name, 'address': address, 'block': block, 'district': district, 'state': state, 'pincode': pin_code_in_data, 'latlng': (lat, long), 'from_time': from_time, 'to_time': to_time, 'fee_type': fee_type } sessions = center_data.get('sessions', []) sessions.append({ 'date': date, 'min_age': min_age, 'capacity': capacity, 'vaccine': vaccine, 'slots': slots }) slots_data[name]['sessions'] = sessions logger.log( INFO, f'For pincode [{pincode}], age [{age}], slots found at [{latest_timestamp}].' ) logger.log(DATA, slots_data) return latest_timestamp, slots_data else: logger.log(INFO, f'No slots found for pincode [{pincode}], age [{age}].') return latest_timestamp, None
def send_notification( user_id, pincode, age, # these two fields need to be as latest as possible, stale info could cause wrong/more notifications respectively pincode_info, user_info, min_time_diff_btw_pos=12 * 3600, min_time_diff_btw_neg=24 * 3600): curr_time = datetime.utcnow() notification_state = get_key(user_info, ['notificationState', f'{pincode}_{age}'], {}) notification_type, response = check_slot_get_response( pincode_info, pincode, age) if notification_type == 'positive': logger.log( DEBUG, f'Slots found for user [{user_id}], pincode [{pincode}], age [{age}].' ) logger.log(DATA, response) if len(response) > 1: message = f"You have slots available in pincode area {pincode}, for {age} year olds, use command 'request {pincode} {age}' to check centers." elif len(response) > 0: message = f"You have slots available in pincode area {pincode}, for {age} year olds." \ f"\n\n{response[0]}" else: logger.log( WARNING, '******** Impossible event, debug immediately. ********') return None, None elif notification_type == 'negative': logger.log( DEBUG, f'Slots NOT found for user [{user_id}], pincode [{pincode}], age [{age}].' ) message = f"No slots available in pincode area {pincode}, for {age} year olds." else: return None, None notify = False if len(notification_state) > 0: last_time_sent = notification_state['timestamp'] last_notification_type = notification_state['type'] time_diff_seconds = (curr_time - last_time_sent).total_seconds() logger.log( DEBUG, f'Found notification state for user [{user_id}], ' f'last time sent [{last_time_sent}], ' f'last notification type [{last_notification_type}], ' f'current notification type [{notification_type}], time difference in seconds [{time_diff_seconds}].' ) if last_notification_type == 'negative' and notification_type == 'positive': notify = True elif last_notification_type == 'negative' and notification_type == 'negative': # send negative notifications repeatedly not closer than 24 hours if time_diff_seconds > min_time_diff_btw_neg: notify = True elif last_notification_type == 'positive' and notification_type == 'negative': notify = True elif last_notification_type == 'positive' and notification_type == 'positive': # send positive notifications repeatedly not closer than 6 hours if time_diff_seconds > min_time_diff_btw_pos: notify = True else: notify = True else: notify = True if notify: logger.log(INFO, f'Notifying user [{user_id}], message [{message}].') telebot.send_message(user_id, message) dbHelper.update_user_info_set( user_id, { f'notificationState.{pincode}_{age}': { 'timestamp': curr_time, 'type': notification_type } }) return notification_type, curr_time else: logger.log(INFO, f'Not notifying user [{user_id}].') return None, None
def process_handler(self, address): ''' Takes the action necssary, according to the message received and dequeues all the chunks and reforms them into a single message ''' global transfer global clientUsername global clientData global usernameExists global clientConnected sendMessage = "" #The message that will be made sendPacket = "" #The packet that will be send sendMessage = "" #Dequeue the chunk and concatinate until end message is received while True: item = transfer[address].get() #If end message is received we break the loop if item == "end": break #Concatinate the chunk into a varaible else: sendMessage += item #Recieve the message, parse it and break into list breakMessage = sendMessage.split() #Check if the client has sent the join message if len(breakMessage) != 0: if breakMessage[0].strip() == "join": #Check if the maximum client limit has been reached if clientConnected == util.MAX_NUM_CLIENTS: self.send(address, "err_server_full", 2) print("disconnected: server full") #If the client limit has not been reached else: #Traverse the client username list to check if the username is already taken for username in clientUsername: #If the username already exits if breakMessage[2].strip() == username.strip(): self.send(address, "err_username_unavailable", 2) usernameExists = True print("disconnected: username not available") break #If the username does not exist if not usernameExists: clientUsername.append(breakMessage[2]) clientUsername.sort(key=str.casefold) clientData[breakMessage[2]] = address clientConnected += 1 print("join:", breakMessage[2]) usernameExists = False #Check if the client has requested the active users list elif breakMessage[0].strip() == "request_users_list": print("request_users_list:", util.get_key(clientData, address)) listCompile = "" #Traverse the client username list for username in clientUsername: listCompile += username + " " self.send(address, "response_users_list", 3, listCompile) #Check if the client wants to send the message elif breakMessage[0].strip() == "send_message": #Check if the message does not contain a character on <numberOfClients> part if not breakMessage[3].isdigit(): self.send(address, "err_unknown_message", 2) print("disconnected:", util.get_key(clientData, address)) #Check if the number of usernames enters is not less than specified in the message elif len(breakMessage) - 4 <= int(breakMessage[3]): self.send(address, "err_unknown_message", 2) print("disconnected:", util.get_key(clientData, address)) #If no format error else: print("msg:", util.get_key(clientData, address)) end = int(breakMessage[3]) + 4 #Traverse through the usernames to which client wants to send the message to senderName = util.get_key(clientData, address) for i in range(4, end): #The destination username exits if clientData.get(breakMessage[i]) is not None: message = senderName + ": " + " ".join( breakMessage[end:]) destinationAddress = ((clientData.get( breakMessage[i]))[0], (clientData.get( breakMessage[i]))[1]) self.send(destinationAddress, "forward_message", 4, message) #The destination username does not exits else: print("msg:", util.get_key(clientData, address), "to non-existent user", breakMessage[i]) #Check if the client wants to send a file elif breakMessage[0].strip() == "send_file": #Check if the message does not contain a character on <numberOfClients> part if not breakMessage[3].isdigit(): self.send(address, "err_unknown_message", 2) print("disconnected:", util.get_key(clientData, address)) #If there is no format error else: print("file:", util.get_key(clientData, address)) end = int(breakMessage[3]) + 4 #Traverse through the usernames to which client wants to send the message to senderName = util.get_key(clientData, address) for i in range(4, end): #The destination username exits if clientData.get(breakMessage[i]) is not None: message = senderName + " " + " ".join( breakMessage[end:]) destinationAddress = ((clientData.get( breakMessage[i]))[0], (clientData.get( breakMessage[i]))[1]) self.send(destinationAddress, "forward_file", 4, message) #The destination username does not exits else: print("file:", util.get_key(clientData, address), "to non-existent user", breakMessage[i]) #Check if the client wants to disconnet elif breakMessage[0].strip() == "disconnect": print("disconnected:", breakMessage[2]) deleteUsername = util.get_key(clientData, address) clientUsername.remove(deleteUsername) del clientData[deleteUsername] clientConnected -= 1 #If the format recieved is something unknown else: print("disconnected:", util.get_key(clientData, address), "sent unknown command") self.send(address, "err_unknown_message", 2) deleteUsername = util.get_key(clientData, address) clientUsername.remove(deleteUsername) del clientData[deleteUsername] clientConnected -= 1