def test_find_metrics(input, input2, expected): from server import find_metrics p = LogIn(username='******') p.save() p = UserData(username='******', image_name=["a.png", "b.png"], image=["imageA", "imageB"], processing_time=["0.5s", "0.2s"], image_size=["400x200", "300x300"], hist_data=["histA", "histB"], upload_date=["2019/12/8", "2019/12/9"]) p.save() p = LogIn(username='******') p.save() p = UserData(username='******', image_name=["a.jpg", "a_hist.jpg"], image=["imageA", "histA"], processing_time=["0.3s", "0.4s"], image_size=["400x100", "200x200"], hist_data=["histA", "histhistA"], upload_date=["2019/12/1", "2019/12/2"]) p.save() result = find_metrics(input, input2) assert result == expected UserData.objects.raw({"_id": "1"}).delete() UserData.objects.raw({"_id": "2"}).delete() LogIn.objects.raw({"_id": "1"}).delete() LogIn.objects.raw({"_id": "2"}).delete()
async def play_game(message): print("{} play game".format(message.chat.username)) user_data = UserData(message.chat.id) print(user_data.get_count_answers()) if user_data.get_count_answers() != 0: db_worker = SQLither(config.database_name) db_worker.insert_answer(message.chat.id, user_data.get_question_id(), message.text) db_worker.update_last_activity(message.chat.id, time.time()) db_worker.close() if user_data.get_count_answers() >= Questions.get_questions_limit(): markup = types.ReplyKeyboardMarkup(one_time_keyboard=False, resize_keyboard=True) markup.add(string_worker.get_yes_button()) markup.add(string_worker.get_no_button()) await send_message(message.chat.id, string_worker.get_ask_feedback(), reply_markup=markup) user_data.delete() return next_question_id = Questions.get_next_random_question_id(user_data.get_answers_id()) user_data.set_question_id(next_question_id) question_text = Questions.get_question(next_question_id) if Questions.is_time_to_praise(user_data.get_count_answers()): await send_message(message.chat.id, string_worker.get_praise(user_data.get_count_answers())) user_data.save() await send_message(message.chat.id, "<b>{}.</b> {}".format(user_data.get_count_answers(), question_text), parse_mode='HTML') if Questions.is_gif_time(user_data.get_count_answers()): await asyncio.sleep(10) await bot.send_chat_action(message.chat.id, 'upload_video') await asyncio.sleep(5) await bot.send_video(message.chat.id, config.pic_begin_game)
def start_session(self): if self.online: print('Hi, this program will ask you to enter the data you want ' + 'encrypted and then give it to you encrypted.') username = raw_input('Please enter your username: '******'Please enter your password: '******'Please enter the data that you want encrypted: ') user_data = UserData(inputted_text, user) encrypter = Encrypter(user_data) encrypted_string = encrypter.encrypt() key = encrypter.get_key() encrypted_data = EncryptedData(encrypted_string, user, key) print('Your encrypted data is: ' + encrypted_data.get_data()) print('The key for your encrypted data is: ' + encrypted_data.get_key()) decrypter = Decrypter(encrypted_data, key) print('Here is the decrypted data: ') print(decrypter.decrypt())
def submit_info(self, instance): # Get all of the values from input popup = Popup( title='Submission Successful!', content=Button( text='Application successfully stored. Click to close!'), size_hint=(None, None), size=(400, 400)) popup.open() popup.content.bind(on_press=popup.dismiss) # Retrieve Data position = self.posInput.text company = self.companyInput.text notified = self.NotifiedInput.text interview = self.InterviewInput.text accepted = self.AcceptedInput.text self.userData = UserData(position, company, notified, interview, accepted) # Insert to database db.insertDB(self.userData) # Clear text inputs self.posInput.text = '' self.companyInput.text = '' self.NotifiedInput.text = '' self.InterviewInput.text = '' self.AcceptedInput.text = ''
async def handle_main_menu_input(message: types.Message): if not message.chat.id in config.admins: user_data = UserData(message.chat.id) if user_data.is_active: return user_data.set_is_active(True) user_data.save() if message.text == string_worker.get_yes_button( ) or message.text == string_worker.get_no_button(): feedback = 0 if message.text == string_worker.get_yes_button(): feedback = 1 db_worker = SQLither(config.database_name) db_worker.insert_feedback(message.chat.id, feedback) db_worker.close() print("{} set {} feedback".format(message.chat.username, feedback)) user_data.set_question_id(-1) user_data.save() await send_message(message.chat.id, string_worker.get_result_message(), reply_markup=types.ReplyKeyboardRemove()) await result(message) else: await play_game(message) user_data = UserData(message.chat.id) user_data.set_is_active(False) user_data.save() else: if message.text == string_worker.get_list_users_button(): db_worker = SQLither(config.database_name) utils.generate_list_users(db_worker) db_worker.close() await bot.send_document(message.chat.id, open(config.users_file, 'rb')) # elif message.text == string_worker.get_delete_data_button(): # db_worker = SQLither(config.database_name) # users = db_worker.select_real_users_in_bot() # for user in users: # user_data = UserData(user.get_user_id()) # user_data.delete() # db_worker.delete_all_data() # db_worker.close() # await send_message(message.chat.id, 'Данные удалено') elif message.text == 'Start cheering users :)': await start_cheering_real_users()
def SelectUserProg(self):#отработка нажатия кнопки пользовательская программа sender=self.sender() name = sender.objectName() point=name[1] self.point=int(point) if self.point==1 and self.Line_65 == 0: self.clear_buttons(self.point) sender.setStyleSheet(metrocss.prog_active) self.AskWindow=UserData(self.user_data_signal, self) self.AskWindow.show() self.AskWindow.move(313, 195) if self.point==2 and self.Line_35 == 0: self.clear_buttons(self.point) sender.setStyleSheet(metrocss.prog_active) self.AskWindow=UserData(self.user_data_signal, self) self.AskWindow.show() self.AskWindow.move(313, 195)
def perform_encrypt(self): self.file_name = self.entry.get() reader = FileReader(self.file_name) string_info = reader.read_file() user_data = UserData(string_info, self.user1) self.e = Encrypter(user_data) key = self.e.get_key() self.encrypted_data = EncryptedData(self.e.encrypt(), self.user1, key) reader.write_to_file(self.encrypted_data.get_data())
def __init__(self): self.completedTransactions = dict() self.plannedTransactions = None self.categories = dict() self.sortingAgent = SortingAgent() self.excelManager = ExcelManager() self.csvAgent = CSVAgent() self.transactionFactory = TransactionFactory() self.plottingDataFactory = PlottingDataFactory() self.userData = UserData()
def main(): user = User('alex10gauthier', 'password99') user_data = UserData('My name is Alex Gauthier', user) encrypter = Encrypter(user_data) encrypted_string = encrypter.encrypt() key = encrypter.get_key() encrypted_data = EncryptedData(encrypted_string, user, key) decrypter = Decrypter(encrypted_data) print(decrypter.decrypt())
def test_is_image_present(stored_username, stored_img_name, username, img_name, expected): from server import is_image_present user = LogIn(username=stored_username) user.save() user_data = UserData(username=user, image_name=[stored_img_name]) user_data.save() value = is_image_present(username, img_name) assert expected == value UserData.objects.raw({"_id": stored_username}).delete() LogIn.objects.raw({"_id": stored_username}).delete()
def get_user_data(): import base64 from flask import request import pickle from UserData import UserData if "data" not in request.cookies: return UserData() else: user = pickle.loads(base64.b64decode(request.cookies["data"])) return user
def main(): exl = ExcelHandler() wb = exl.open_workbook("products.xlsx") exl.assign_sheets(wb) diet = DietManager() usrData = UserData() usrData.set_parameters("Piotrek", "male", 21, 82, 185) usrData.write_to_file() print(diet.calculate_bmi(usrData)) print(diet.calculate_limit(usrData)) diet.what_you_ate_today("banan", 300, exl, usrData)
def initialize_keypaths(base_keypath: str, base_datapath: str): # check if the keypath and datapaths exist, if not create a new directory to match if not os.path.exists(base_keypath): logger.warning( f"base_keypath {base_keypath} does not exist. Creating directory") os.makedirs(base_keypath) if not os.path.exists(base_datapath): logger.warning( f"base_datapath {base_datapath} does not exist. Creating directory" ) os.makedirs(base_datapath) # initialize output dict output: Dict[str, UserData] = {} # keys and databases are filenames of the form username.extension and should match # i.e for every username.db there is a username.key keys: List[str] = [ filename for filename in os.listdir(base_keypath) if filename.split('.')[-1] == "key" ] databases: List[str] = [ filename for filename in os.listdir(base_datapath) if filename.split('.')[-1] == "db" ] # if the above constraint is met then the two lists of paths should be the same length if len(databases) != len(keys): raise ValueError("Keys and databases out of sync") # for each username in the keys list there should be a matching db file, if not then an error is raised for key in keys: if '.'.join([key.split('.')[0], "db"]) not in databases: raise ValueError("Keys and databases out of sync ") # now that we know keys and databases represent the same users and are in sync # we can build our output paths using the usernames and known extensions # each entry of output should look like this # mycicle: UserData({ # keypath: /home/mycicle/.secrets_manager/keys/mycicle.key # datapath: /home/mycicle/.secrets_manager/data/mycicle.data # }) # the path should update to the correct "home" directory for the user's OS # and the "/" should be properly replaced with a "\" on Windows for key in keys: username: str = key.split('.')[0] output[username] = UserData( join(base_keypath, key), join(base_datapath, '.'.join([username, "db"]))) return output
def test_is_first_upload(stored_username, username, expected): from server import is_first_upload user = LogIn(username=stored_username) user.save() user_data = UserData(username=user, image_name=['.'], image=['.'], processing_time=['.'], image_size=['.'], hist_data=['.'], upload_date=['.']) user_data.save() value = is_first_upload(username) assert expected == value UserData.objects.raw({"_id": stored_username}).delete() LogIn.objects.raw({"_id": stored_username}).delete()
def test_inverted_image_upload(username, filepath, expected): from server import inverted_image_upload user = LogIn(username=username) user.save() user_data = UserData(username=user, image_name=['.'], image=['.'], processing_time=['.'], image_size=['.'], hist_data=['.'], upload_date=['.']) user_data.save() inverted_image_upload(username, filepath) users = UserData.objects.raw({"_id": username}) stored_name = '' for user in users: stored_name = user.image_name assert expected == stored_name[1] UserData.objects.raw({"_id": username}).delete() LogIn.objects.raw({"_id": username}).delete()
print(channel_secret, file=sys.stderr) print(channel_access_token, file=sys.stderr) line_bot_api = LineBotApi(channel_access_token) handler = WebhookHandler(channel_secret) static_tmp_path = os.path.join(os.path.dirname(__file__), 'static', 'tmp') # ========================= whisper独自のフィールド ======================== from UserData import UserData from PlantAnimator import PlantAnimator from beaconWhisperEvent import BeaconWhisperEvent from datetime import datetime user_data = UserData() current_plant = "" plant_animator = PlantAnimator(user_data) # ========================================================================= # function for create tmp dir for download content def make_static_tmp_dir(): try: os.makedirs(static_tmp_path) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(static_tmp_path): pass else:
def original_upload(username, filepath): """Performs encoding and uploads to database along with associated data metrics (upload time, processing time, histogram, size). Checks to see if username is already associated with a UserData document and uploads accordingly. Args: username (str): username to upload to in database filepath (str): filepath of image to be processed and encoded Returns: None """ # Read original image from filepath image = skimage.io.imread(filepath) # Process image and encode it. start_time = time.time() image_encode = encode_array(image) processing_time = str(time.time() - start_time) # Create image name image_name = img_name_from_filepath(filepath, "_original") # Calc image size image_size = get_num_pixels(image) # Get date and time upload_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S:%f") # Calc histogram data. Produces {"red": ndarray, "green....} # Use each color spectrum for analysis via processing, then # concatenate back together with img = np.dstack(red, green, blue) hist_data = pixel_histogram(image) hist_encode = encode_dict(hist_data) # Check if previous images exist if is_first_upload(username): # If first upload, create document user = UserData(username=username, image_name=[image_name], image=[image_encode], processing_time=[processing_time], image_size=[image_size], hist_data=[hist_encode], upload_date=[upload_date]) user.save() else: # Save image to database UserData.objects.raw({ "_id": username }).update({ "$push": { "image_name": image_name, "image": image_encode, "processing_time": processing_time, "image_size": image_size, "hist_data": hist_encode, "upload_date": upload_date } }) return
def main(): # Menu trybun = Trybun() dictation = Dictation() trybun.say_something("Witaj w Dajet. Aut. Laud.") usrData = UserData() usrData.remove_data_from_file() dm = DietManager() sarmata = SarmataVoiceRecognition() sarmata_numbers = SarmataVoiceRecognitionNumbers() open_date = datetime.datetime.now().strftime("%Y-%m-%d") dm.fm.write_date_to_file(open_date, "open_date.txt") while True: data, is_something = usrData.read_from_file() if is_something == True: usrData.set_params_from_file(data) trybun.say_something( "Witaj, %s. wybierz jedną z opcji. liczenie kalorii. liczenie BEEMI. dzienne zapotrzebowanie. ile już zjadłeś. lub wyjście z programu" % data['name']) # 1, 2 lub 3 res_semantic_interpretation = sarmata.menu_choice_recognition( "grammars/menu.abnf") #res_semantic_interpretation = '5' if res_semantic_interpretation == '1': trybun.say_something("Wybrałeś opcję. Liczenie Kalorii.") while True: # podawanie produktu trybun.say_something("podaj nazwę produktu") produkt = dictation.dictation_recognize() trybun.say_something("podaj wagę produktu w gramach") waga = sarmata_numbers.menu_choice_recognition( "grammars/numbers.abnf") waga = int(waga) if waga == -1: trybun.say_something("Spróbuj jeszcze raz.") continue error_result = dm.what_you_ate_today( produkt, waga, usrData, trybun) if error_result == -1: trybun.say_something("Spróbuj jeszcze raz.") continue # dodawanie kolejnego produktu albo wracanie, na tak lub nie ---------------------- trybun.say_something( "Chcesz dodać kolejny produkt, czy wrócić do menu głownego?" ) res_semantic_interpretation = sarmata.menu_choice_recognition( "grammars/next_product.abnf") if res_semantic_interpretation == '1': continue # jak ktoś powie głupotę to i tak do menu elif res_semantic_interpretation == '2': break else: break elif res_semantic_interpretation == '2': trybun.say_something("Wybrałeś opcje. Liczenie beemi") bmi = dm.calculate_bmi(usrData) trybun.say_something("Twoje beemi wynosi %s" % bmi) continue elif res_semantic_interpretation == '3': trybun.say_something("Wybrałeś opcję. Dzienne zapotrzebowanie") limit = dm.calculate_limit(usrData) trybun.say_something("Twój dzienny limit kalorii wynosi %s" % limit) continue elif res_semantic_interpretation == '4': dm.get_today(trybun, usrData) continue elif res_semantic_interpretation == '5': trybun.say_something("Do widzenia %s" % data['name']) break else: trybun.say_something("Spróbuj jeszcze raz!") continue else: trybun.say_something("Podaj swoje dane.") while True: trybun.say_something("Jak masz na imię?.") reco = dictation.dictation_recognize() if reco == -1: continue trybun.say_something("Spróbuj jeszcze raz") else: name = reco break while True: trybun.say_something("Podaj płeć.") res_semantic_interpretation_gender = sarmata.menu_choice_recognition( "grammars/gender.abnf") if res_semantic_interpretation_gender == -1: trybun.say_something("Spróbuj jeszcze raz") continue else: gender = res_semantic_interpretation_gender break while True: trybun.say_something("Ile masz lat?") reco = sarmata_numbers.menu_choice_recognition( "grammars/numbers.abnf") if reco == -1: trybun.say_something("Spróbuj jeszcze raz") continue else: age = reco break while True: trybun.say_something("Ile ważysz?") reco = sarmata_numbers.menu_choice_recognition( "grammars/numbers.abnf") if reco == -1: trybun.say_something("Spróbuj jeszcze raz") continue else: weight = reco break while True: trybun.say_something("Ile masz wzrostu w centymetrach?") reco = sarmata_numbers.menu_choice_recognition( "grammars/numbers.abnf") if reco == -1: trybun.say_something("Spróbuj jeszcze raz") continue else: height = reco break # setData usrData.set_parameters(name, gender, age, weight, height) usrData.write_to_file()
'train': transforms.Compose([ transforms.RandomResizedCrop (224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]), 'val': transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]), } dsets = {x: UserData(img_path=data_dir, txt_path=(label_txt + x + '.txt'), data_transforms=data_transforms, dataset=x) for x in ['test', 'train']} dset_loaders = {x: torch.utils.data.DataLoader(dsets[x], batch_size=10, shuffle=True, num_workers=25)#num_workers 用多少个子进程加载数据,这里用了25个子进程 for x in ['test', 'train']} data_loader_train=dset_loaders['test'] data_loader_test=dset_loaders['train'] def image_visible(): images, labels = next(iter(data_loader_train))#得到一个所有地images和label的列表 print("one batch dim:", images.size()) # for i, (images, labels) in enumerate(data_loader_train): img = utils.make_grid(images[0:4]) # 绘制四个 # 如果要使用matplotlib显示图片,必须将(channel,height,weight)转换为(height,weight,channel) img=img.numpy().transpose(1,2,0) mean=[0.485, 0.456, 0.406] std=[0.229, 0.224, 0.225]
#!/usr/bin/env python3 import base64 import functools import os import pickle import requests import flask from UserData import UserData cookies = {"data": base64.b64encode(pickle.dumps(UserData())).decode()} response = requests.get("http://localhost:6001/", cookies=cookies) response = requests.get("http://localhost:6001/solve") print(response.text)
def get_jwt(self,user_position_in_list): if(self.password_match): user_data = UserData(user_position_in_list) print('===========>>>>',user_data.getUserData()) jwt = CreateJwt(user_data.getUserData()) return jwt.jwt_created()
def main(): user = User('alex10gauthier', 'password99') user_data = UserData('My name is Alex Gauthier', user) encrypt = Encrypter(user_data) print(encrypt.encrypt())
def create_user(username: str): """ Generate a new key and salt combination for a new user Generate a database with an empty table for that user Save the key, salt combination to disk """ print( "You are about to input the password used to encrypt all of your data. Make it strong and write it down" ) print( "Nobody will be able to recover your password or your data if you forget it." ) print( "You will be able to recover your private key from your password and a ranomly generated number called 'salt'" ) print(""" To make your data more resistant to brute force attacks, we add 'salt' to your password. Salt is a random sequence of numbers that can be used to obscure your true password. You will have to write down your 'salt' as well as your password If you want to recover your private key you will need to input your 'salt' as well. """) password: str = str( input("Please input your new user password for initialization: ")) # while True: # check_password = input(f"Your password is: {password}\nEnter your password to confirm that you have it copied down correctly:\n ") # if check_password == password: # print("Correct") # break # else: # print(f"Incorrect, the correct password is: \n{password}") # continue key_generator: KeyGen = KeyGen() key, salt = key_generator.generate_new(password) print(f"Your salt is: {salt.hex()}") while True: check_salt = input( f"Your salt value is: {salt.hex()}\nEnter your salt value to confirm that you have it copied down correctly:\n " ) if check_salt == salt.hex(): print("Correct") break else: print(f"Incorrect, the correct salt value is: \n{salt.hex()}") continue _ = input( "Press 'enter' to continue once you have written down your salt and your password.\nTHIS IS THE LAST TIME YOU WILL BE ABLE TO SEE THEM" ) private_keypath: str = join(base_keypath, '.'.join([username, 'key'])) print(f"saving private key to: {private_keypath}") user_datapath: str = join(base_datapath, '.'.join([username, 'db'])) print(f"saving user data to: {user_datapath}") key_salt_str: str = key.hex() + salt.hex() with open(private_keypath, 'w') as file: file.write(key_salt_str) conn = sqlite3.connect(user_datapath) c = conn.cursor() c.execute(""" CREATE TABLE accounts (application text, password text, mnemonic text, pin text, additional text) """) conn.commit() conn.close() keypaths[username] = UserData(private_keypath, user_datapath)
from UserData import UserData from Ratings import Ratings from Movies import Movies import os if __name__ == '__main__': root_path = 'C:\Users\p\Documents' input_files_path = os.path.join(root_path, 'PycharmProjects\SocialCommunicationNetworks\ml-1m') output_files_path = os.path.join(root_path, 'PycharmProjects\SocialCommunicationNetworks\ml-1m\output') userdata = UserData(input_files_path, output_files_path) userdata.prepare_user_data() movies = Movies(input_files_path, output_files_path) movies.prepare_user_data() ratings = Ratings(input_files_path, output_files_path) ratings.prepare_user_data()
async def start(message: types.Message): print("{} has id {}".format(message.chat.username, message.chat.id)) # for question in Questions.questions: # await send_message(message.chat.id, question, parse_mode='HTML') if message.chat.id in config.admins: markup = types.ReplyKeyboardMarkup(one_time_keyboard=False, resize_keyboard=True) markup.add(string_worker.get_list_users_button()) # markup.add(string_worker.get_delete_data_button()) await send_message(message.chat.id, string_worker.get_instructions(), parse_mode='HTML', reply_markup=markup) return else: # user_data = UserData(message.chat.id) # user_data.delete() user_data = UserData(message.chat.id) user_data.set_is_active(True) user_data.save() db_worker = SQLither(config.database_name) if db_worker.is_user_exist(message.chat.id): await send_message(message.chat.id, string_worker.get_pass_one_time()) return else: db_worker.update_last_activity(message.chat.id, time.time()) db_worker.insert_user(message.chat.id, message.chat.first_name, message.chat.last_name, message.chat.username) db_worker.close() markup = types.ReplyKeyboardRemove() await send_message(message.chat.id, string_worker.get_hello(), parse_mode='HTML', reply_markup=markup) await asyncio.sleep(10) await bot.send_chat_action(message.chat.id, 'upload_video') await asyncio.sleep(5) await bot.send_video(message.chat.id, config.pic_begin_game) await asyncio.sleep(5) next_question_id = Questions.get_next_random_question_id( user_data.get_answers_id()) user_data.set_question_id(next_question_id) question_text = Questions.get_question(next_question_id) await send_message(message.chat.id, "<b>{}.</b> {}".format( user_data.get_count_answers(), question_text), parse_mode='HTML') user_data.set_is_active(False) user_data.save()