def open_filechooser(fc_type, liststore): if fc_type == "file": title = "Select file" fc_action = Gtk.FileChooserAction.OPEN elif fc_type == "folder": title = "Select folder" fc_action = Gtk.FileChooserAction.SELECT_FOLDER file_dialog = Gtk.FileChooserDialog(title=title, action=fc_action, parent=None) file_dialog.set_select_multiple(True) # Set buttons for dialog file_dialog.add_buttons("Cancel", Gtk.ResponseType.CANCEL, "Open", Gtk.ResponseType.OK) response = file_dialog.run() # Add item if response == Gtk.ResponseType.OK: functions.add_item(liststore, file_dialog.get_filename()) # Close dialog after finishing file_dialog.destroy()
def group_msg(msg): if config.LISTEN_GROUPS: print("From the group : ") name = msg.member.name time = msg.receive_time text = msg.text # print(msg.member.name) # print(msg.receive_time) message = msg.member.name + ' : ' + msg.text print(message) globvar.dict_msg, globvar.msg_id = f.add_item(globvar.dict_msg, globvar.msg_id, name, time, text) print('id : ', globvar.msg_id) if regex.is_question(text): globvar.dict_qs = f.add_question(globvar.dict_qs, globvar.msg_id, name, time, text) localtime = f.get_localtime() globvar.dict_msg, globvar.dict_qs = f.clear_dict( localtime, config.INITIALIZE_TIME, globvar.dict_msg, globvar.dict_qs) # test print(globvar.dict_msg)
def friends_msg(msg): if config.LISTEN_FRIENDS: print("From a friend : ") name = msg.sender.name time = msg.receive_time text = msg.text # print(msg.sender.name) # print(msg.receive_time) message = msg.sender.name + ' : ' + msg.text print(message) globvar.dict_msg, globvar.msg_id = f.add_item(globvar.dict_msg, globvar.msg_id, name, time, text) print('id : ', globvar.msg_id) if regex.is_question(text): globvar.dict_qs = f.add_question(globvar.dict_qs, globvar.msg_id, name, time, text) localtime = f.get_localtime() globvar.dict_msg, globvar.dict_qs = f.clear_dict( localtime, config.INITIALIZE_TIME, globvar.dict_msg, globvar.dict_qs)
# Filling the AG table # Opening the reader to extract each unique pair of [Campaign + Ad Group] and use it to create a table with open('Ad_Report2.csv', 'r') as csv_file: csv_dict_reader = csv.DictReader(csv_file) for row in csv_dict_reader: if functions.check_if_exists( c, 'Ad_Groups', { 'CAMPAIGN_NAME': row['Campaign'], 'AD_GROUP_NAME': row['Ad group'] }): continue else: functions.add_item( conn, c, 'Ad_Groups', { 'CAMPAIGN_NAME': row['Campaign'], 'AD_GROUP_NAME': row['Ad group'] }) # Filling the Ads table # Opening the reader to extract content and dumping into DB with open('Ad_report2.csv', 'r') as csv_file: csv_dict_reader = csv.DictReader(csv_file) no_duplicate_found = True for row in csv_dict_reader: keys = list(row.keys()) # We don't want to include Responsive search ads in our P-Value calculator, # so if one of those appears, we will break the inner loop # then continue the outer loop for item in keys: if item.startswith(
while functions.is_number(variables[1]) == False: print("Value of quantity is not a number!\nPleas fix it") variables[1] = input(">: ") while functions.is_number(variables[3]) == False: print("Value of price is not a number!\nPleas fix it") variables[3] = input(">: ") if functions.is_in_list(variables[0], items) == True: print( "Item is already in warehouse!\nIf you want change item status use 'update item ...'" ) elif functions.confirm_choice() == True: logging.debug(f"adding {variables[0]}\n") x = functions.add_item(variables[0], variables[1], variables[2], variables[3]) items.append(x) change = True print("Item is added to warehouse") #---------------- elif 'update item' in x: item_name = x[x.rfind(' '):].strip() for item in items: if item_name == item['name']: print(item, '\n') x = input("What you want change? >: ") while x not in item.keys(): x = input("Can you write again? >: ")
def fatsecret(food): # client authorization, getting token client_id = '8f3d9de1df974e8d9c3452d131cd3187' client_secret = '9c8513c5e9de4daf8206b8c792273048' token_url = 'https://oauth.fatsecret.com/connect/token' auth = HTTPBasicAuth(client_id, client_secret) client = BackendApplicationClient(client_id=client_id) oauth = OAuth2Session(client=client) token = oauth.fetch_token(token_url=token_url, auth=auth) # accessing FatSecret API - Search endpoint = "https://platform.fatsecret.com/rest/server.api" headers = { 'Authorization': "Bearer {0}".format(token["access_token"]), } data_search = { 'method': 'foods.search', 'search_expression': food, 'format': 'json', 'content-type': 'application/json' } r_search = requests.post(endpoint, headers=headers, data=data_search) j_search = json.loads(r_search.text) # list of results search = j_search['foods']['food'] choice = '' choice_id = 0 choices = {} for i in range(len(search)): if search[i]['food_type'] == 'Generic': words = search[i]['food_name'].lower().split(' ') for m in words: if m == food: choices[search[i]['food_name']] = search[i]['food_id'] print(f"{i + 1} - {search[i]['food_name']}") while True: selected = input("\nSelect item (case sensitive): ").strip() if selected == 'q': break if selected not in choices: print("No such item, try again.") else: choice = selected choice_id = int(choices[choice]) break data_get = { 'method': 'food.get', 'food_id': choice_id, 'format': 'json', 'content-type': 'application/json' } r_get = requests.post(endpoint, headers=headers, data=data_get) j_get = json.loads(r_get.text) get_servings = j_get['food']['servings']['serving'] ids = [] for i in range(len(get_servings)): ids.append(i + 1) serving_ids = {} for i in range(len(get_servings)): serving_ids[get_servings[i]['measurement_description']] = ids[i] print(f"{serving_ids[get_servings[i]['measurement_description']]} \ - {get_servings[i]['measurement_description']}") while True: serving = input("\nSelect serving (type its number): ").lower().strip() if serving == 'q': break if serving == '': print('Serving size must be specified.') else: try: serving = int(serving) except ValueError: print("Use serving's number only.") else: selected_serving = get_servings[serving] p = float(selected_serving['protein']) c = float(selected_serving['carbohydrate']) f = float(selected_serving['fat']) cal = float(selected_serving['calories']) serv = selected_serving choice = choice.lower() print(f"\nAdded {choice.lower()} from global to local database.") functions.add_item(choice, p=p, c=c, f=f, cal=cal) break
def on_button_add_clicked(self, button): path = builder.get_object("entry_path").get_text() functions.add_item(liststore_files, path)
def main(): new_day = input('New day? (y/n) ').lower().strip() if new_day == 'y': functions.reset_day() functions.incr_days_count() print(f'\nWelcome to day {functions.days_count()}!') elif new_day == 'n': print(f'\nWelcome to day {functions.days_count()}!') else: return # starting point print("Your current nutrition values:") functions.check_current() print("") print("Available commands:") functions.show_commands() # getting user's initial input - main body of the program while True: action = input("\nEnter command (enter 'q' anytime to exit program): " ).lower().strip().split(' ') if action[0] == 'q': break # getting data loaded, more specifically - list of commands with open('data.json', 'r') as file: data = json.load(file) if action[0] not in data["commands"]: print( "No such command. Type 'commands' to see all available options." ) else: # linking commands with actions if action[0] == 'add': if len(action) != 2: print("Usage: add item_name") continue with open('data.json', 'r') as f: database = json.load(f) # logic for adding new item to database vs getting that item from db into eaten today list # the following only gives option to search external DB when no item was found in data.json # the more user adds to data.json, the less there will be a need to call external API new_item = action[1].lower() if new_item not in database["DATABASE"]: print( f'Unable to find {new_item} in local database. You can:' ) print(f"- Enter its nutrients directly (enter)") print(f"- Search for it in global database (search)") add_to_database = input( "\nType 'enter' or 'search': ").lower().strip() if add_to_database == 'q' or add_to_database == '': continue if add_to_database == 'enter': p, c, f, cal = '', '', '', '' nutr = [p, c, f, cal] exit_flag = False # flag to avoid the need to enter all 4 values if one of them was quit not_all_four = False # flag to prohibit values to go into database if not all 4 were entered exited = False # flag to avoid displaying a message that all 4 values are needed for i in NUTRITION: if exit_flag: break while True: nutr[NUTRITION.index(i)] = input( f"{i}: ").strip() # changes flags which results in returning to main entry field if nutr[NUTRITION.index(i)] == 'q': exit_flag = True not_all_four = True exited = True break if nutr[NUTRITION.index(i)] == '': print( "Cannot skip values. Enter 0 for empty value." ) else: try: nutr[NUTRITION.index(i)] = int( nutr[NUTRITION.index(i)]) except ValueError: print("Please use only digits.") else: break if not exited: # the following condition is questionable, I will leave it here for now just in case # ...'cause it's working :D if not_all_four: print( "Need all 4 nutrition values to continue.") else: print(f'Added {new_item} to the database.') functions.add_item(new_item, p=nutr[0], c=nutr[1], f=nutr[2], cal=nutr[3]) print("\nTo reach today goal, you need:") functions.show_left() elif add_to_database == 'search': global_DB_apis.fatsecret(new_item) print("\nTo reach today goal, you need:") functions.show_left() else: functions.add_item( new_item, p=database["DATABASE"][new_item]["Proteins"], c=database["DATABASE"][new_item]["Carbs"], f=database["DATABASE"][new_item]["Fats"], cal=database["DATABASE"][new_item]["Calories"]) print("\nTo reach today goal, you need:") functions.show_left() elif action[0] == 'remove': if len(action) != 2: print("Usage: remove item_name") continue existing_item = action[1] functions.remove_item(existing_item) elif action[0] == 'current': print('\nCurrent day values:') functions.check_current() elif action[0] == 'reset': confirm_reset = input( 'Are you sure you want to reset? (y/n) ').lower().strip() if confirm_reset == 'q': continue if confirm_reset == 'y': functions.reset_day() elif action[0] == 'items': # checking if list of items is empty with open('data.json', 'r') as another_file: another_data = json.load(another_file) if another_data['eaten_today'] != {}: print('\nConsumed today:') functions.show_items() else: another_item = input( "Today's list is empty. Would you like to add a new item? \ (y/n) ").lower().strip() if another_item == 'q': continue if another_item == 'y': exit_choosing_product = False # flag to exit to main entry field after adding a new item while True: if exit_choosing_product: break new_item = input( '\nName of product: ').lower().strip() if new_item == 'q': break if new_item not in database["DATABASE"]: print( f'Unable to find {new_item} in local database. You can:' ) print( f"- Enter its nutrients directly (enter)") print( f"- Search for it in global database (search)" ) add_to_database = input( "\nType 'enter' or 'search': ").lower( ).strip() if add_to_database == 'q' or add_to_database == '': continue if add_to_database == 'enter': p, c, f, cal = '', '', '', '' nutr = [p, c, f, cal] exit_flag = False not_all_four = False exited = False for i in NUTRITION: if exit_flag: break while True: nutr[NUTRITION.index(i)] = input( f"{i}: ").strip() # changes flags which results in returning to main entry field if nutr[NUTRITION.index(i)] == 'q': exit_flag = True not_all_four = True exited = True exit_choosing_product = True break if nutr[NUTRITION.index(i)] == '': print( "Cannot skip values. Enter 0 for empty value." ) else: try: nutr[NUTRITION.index( i)] = int( nutr[NUTRITION. index(i)]) except ValueError: print( "Please use only digits." ) else: break if not exited: if not_all_four: print( "Need all 4 nutrition values to continue." ) else: print( f'Added {new_item} to the database.' ) functions.add_item(new_item, p=nutr[0], c=nutr[1], f=nutr[2], cal=nutr[3]) print( "\nTo reach today goal, you need:" ) functions.show_left() elif add_to_database == 'search': global_DB_apis.fatsecret(new_item) print("\nTo reach today goal, you need:") functions.show_left() break else: functions.add_item( new_item, p=database["DATABASE"][new_item] ["Proteins"], c=database["DATABASE"][new_item]["Carbs"], f=database["DATABASE"][new_item]["Fats"], cal=database["DATABASE"][new_item] ["Calories"]) print("\nTo reach today goal, you need:") functions.show_left() break elif action[0] == 'daily': print('\nYour daily goal:') functions.show_daily_needed() elif action[0] == 'left': print("\nLeft to achieve today's goal:") functions.show_left() elif action[0] == 'startover': print('\nProgress has been reset.') functions.reset_days_count() elif action[0] == 'commands': print('\nAvailable commands:') functions.show_commands()