def __init__(self, stages, arrival_rate, customer_selection_strategy, agent_selection_strategy, enable_gui=True, debug=False): self.stages = stages self.current_time = 0 self.customers = [] self.events_queue = [] self.agents = [] self.arrival_rate = arrival_rate self.customer_selection_strategy = customer_selection_strategy self.agent_selection_strategy = agent_selection_strategy self.debug = debug # new customers arrive in this state (all 3 stages are pending) initial_status = {k: "pending" for k, v in stages.items()} num_customers = self.arrival_rate(0) # invoking the lambda at t=0 for i in range(num_customers): xpos = 250 + 60 * (i % 12) ypos = 250 + 50 * (i / 12) customer = Customer("c{}".format(i), dict(initial_status), xpos, ypos) # assuming getting a token takes 1 second customer.token_time = i customer.waiting_since = i self.customers.append(customer) event = Event(type="arrived", agent=None, customer=customer, time=i) bisect.insort(self.events_queue, event) # insert in sorting order # For each stage, create agents for i, s in enumerate(stages.keys()): for j in range(stages[s].num_agents): agent = Agent(stage=stages[s], id="{}{}".format(s, j), x=300, y=300) self.agents.append(agent) # Arrange all agents in a circle around the waiting area # Need to iterate over *all* agents and not stage-wise if enable_gui: for i, a in enumerate(self.agents): a.position_x = 600 + 560 * cos(i * TAU / len(self.agents)) a.position_y = 600 + 560 * sin(i * TAU / len(self.agents))
def test_statement(): checkingAccount = createBankAccount(CHECKING) savingsAccount = createBankAccount(SAVINGS) henry = Customer("Henry").openAccount(checkingAccount).openAccount( savingsAccount) checkingAccount.deposit(100.0) savingsAccount.deposit(4000.0) savingsAccount.withdraw(200.0) assert_equals( henry.getStatement(), "Statement for Henry" + "\n\nChecking Account\n deposit $100.00\nTotal $100.00" + "\n\nSavings Account\n deposit $4000.00\n withdrawal $200.00\nTotal $3800.00" + "\n\nTotal In All Accounts $3900.00")
def show_record(cursor, query): try: cursor.execute(query) records = cursor.fetchall() if cursor.rowcount == 0: print("No Matching Records") return record = records[0] customer = Customer().create_from_record(record) customer.print_full() return customer except mysql.connector.Error as err: print(err)
def get_customer(self, phone): read_book = xlrd.open_workbook(self.filename) w_sheet = read_book.sheet_by_index(1) row = self.find_customer_row(phone) first_name, last_name, postcode, phone, email, order_numbers, total_orders, money_spent = w_sheet.row_values( row) if not order_numbers: order_numbers = [] else: order_numbers = str(int(order_numbers)) order_numbers = map(int, order_numbers.split(",")) return Customer(first_name, last_name, postcode, phone, email, order_numbers, int(total_orders), float(money_spent))
def testCreateCustomer(self): cust = Customer(**postBody) self.assertEqual('test', cust.username) self.assertEqual('*****@*****.**', cust.email) self.assertEqual('password', cust.password) self.assertEqual('firstname', cust.firstname) self.assertEqual('lastname', cust.lastname) self.assertEqual('1234567890', cust.phonenumber) #self.assertEqual(custid, cust.custIDs) print(cust) print()
def test_c_transfer(self): account1 = Customer("christian", "199290877464727", "780987122", 2000, 1234) amount = 50000 self.assertGreater(amount, account1.balance) testamount = account1.c_transfer(50000, 1234) self.assertEqual(testamount, 0) testpassword = account1.c_transfer(1000, 2134) self.assertEqual(testpassword, "")
def checkLogin(): phone_no = input("Phone no :") pwd = input("Password :"******"o") print(res) val = cust.getAllOrders() print(val)
def generate_customer(self): ''' Given a mean and covariance matrix, the event rates for the customer are drawn from the multi-variate gaussian distribution. :return: a Custoemr object ''' customer_rates = np.random.multivariate_normal(mean=self.behave_means, cov=self.behave_cov) customer_rates = customer_rates.clip( min=self.min_rate) # clip : no negative rates! new_customer = Customer(customer_rates) # print(customer_rates) return new_customer
def main(): print('**********Welcome to Bank of America***********\n') print( '1- Do you want to signup as a customer\n2- Do you want to Login as a customer\n' ) user_choice = input('Choose from above and Enter: ') username = input('\nEnter your username: '******'2': file = open('signup.pickle', 'rb') signup = pickle.load(file) file.close() if username in signup.keys(): if signup[username][0] == input('Enter your account Password: '******'\n************Login Successfully!**********\n') decision = input( 'Do you want to see your Personal Information (y/n): ' ).lower() if decision == 'y': obj = Customer() obj.view_personal_information(username) Bank(username) elif decision == 'n': Bank(username) else: print( '\n**********Invalid Input**********\n\n*****Exiting!******' ) else: print('\n**********Invalid Password!**********') else: print('\n**********Invalid username!************') elif user_choice == '1': new_customer = Customer() new_customer.get_personal_information(username) print('*********You are automatically logged in**************\n') Bank(username)
def initialize_customers_and_depot(): global depot, maximum_allowed_vehicles, vehicle_capacity f = open(FILE_NAME, "r") lines = f.readlines() maximum_allowed_vehicles, vehicle_capacity = [ int(element) for element in lines[4].split(" ") if element != '' ] for line in lines[9:]: args = [int(element) for element in line.split(" ") if element != ''] customer = Customer(*args) customers.append(customer) depot = customers[0] depot.is_depot = True
def load_scenario(self, scenario_file_name): """Load a scenario from the scenario_file_name and store it in _scenario :param scenario_file_name: Name of the scenario file :type scenario_file_name: str :rtype: None """ scenario_file = open(scenario_file_name) for current_line in scenario_file: new_customer = Customer(current_line.strip()) self._scenario.append(new_customer) scenario_file.close()
def generate_customer(self,start_of_month): ''' Given a mean and covariance matrix, the event rates for the customer are drawn from the multi-variate gaussian distribution. subtract 0.5 and set min at 0.5 per month, so there can be very low rates despite 0 (1) min in log normal sim :return: a Custoemr object ''' customer_rates=np.random.multivariate_normal(mean=self.log_means,cov=self.behave_cov) customer_rates=self.exp_fun(customer_rates) customer_rates = np.maximum(customer_rates-0.667,0.333) new_customer= Customer(customer_rates,channel_name=self.version,start_of_month=start_of_month) # print(customer_rates) return new_customer
def test_returnBike_for_invalid_numOfBikes(self): shop = BikeRental(10) customer = Customer() customer.rentalTime = datetime.now() customer.rentalBasis = 1 #invalid number of bikes customer.bikes = 0 request = customer.returnBike() self.assertEqual(shop.returnBike(request), None) self.assertIsNone(shop.returnBike(request))
def startUp(sheet): i = 1 while (i < int(sheet.row_count)): i = i + 1 if (sheet.row_values(i) == ''): break values_list = sheet.row_values(i) customer = Customer(values_list[0]) customer.renewal_date = values_list[1] customer.email = values_list[2] customer.phone = values_list[3] if (customer.name == ""): break customer_list.append(customer)
def run_simulation(): """The central method called in main.py.""" customer = Customer() soda_machine = SodaMachine() while True: user_option = user_interface.simulation_main_menu() if user_option == 1: soda_machine.begin_transaction(customer) elif user_option == 2: customer.check_coins_in_wallet() elif user_option == 3: customer.check_backpack() elif user_option == 4: quit()
def main(): #customer 1 data print("Customer 1") email = input("Enter email address: ") customer1 = Customer(email) customer1.input_info() customer1.verify_info() customer1_output_string = customer1.output_info() print() #customer 2 data print("Customer 2") email = input("enter email address: ") customer2 = Customer(email) customer2.input_info() customer2.verify_info() customer2_output_string = customer2.output_info() print() #export data to text file customer_output_string = customer1_output_string + customer2_output_string output_file = open('customers.txt', 'w') output_file.write(customer_output_string) output_file.close() print("Data of two customers written to the file 'customer.txt'.")
def read_customer(self): try: self.show("enter first name: ") fname = self.read_string() self.show("enter second name: ") sname = self.read_string() self.show("enter available money that you have: ") money = self.read_int() self.show("enter you driv categories: ") catigories = self.read_string().split() return Customer(sname, fname, money, catigories) except: return None
def test_1() -> None: """ get_created_date """ customer: Customer = Customer( dt.datetime(2018, 1, 1, 0, 0, 0, tzinfo=dt.timezone.utc)) tzone: dt.timezone = dt.timezone(dt.timedelta(hours=0)) assert get_created_date(customer, tzone) == dt.date(2018, 1, 1) tzone = dt.timezone(dt.timedelta(hours=1)) assert get_created_date(customer, tzone) == dt.date(2018, 1, 1) tzone = dt.timezone(dt.timedelta(hours=-1)) assert get_created_date(customer, tzone) == dt.date(2017, 12, 31)
def main(self): # criando N registros c1 = Customer(45617387911, "João 2", 2000.50, True) c2 = Customer(98712387912, "Maria", 1180.50, True) c3 = Customer(45678932113, "Zuleide", 700, True) # salvando no banco de dados c1.save() c2.save() c3.save() # obtendo clientes para cálculo da média clientes = Customer().get_by_saldo(560, (1500, 2700)) qtde = len(clientes) if qtde > 0: total = 0 for cliente in clientes: total += cliente.vl_total print(cliente) print() print("Média Final: R$ %.2f" % (total / qtde)) else: print("Nenhum cliente cadastrado com essas especificações!")
def test_returnCar_for_invalid_rentalBasis(self): # create a shop and a customer shop = CarRental(10) customer = Customer() # create valid rentalTime and cars customer.rentalTime = datetime.now() customer.cars = 3 # create invalid rentalbasis customer.rentalBasis = 8 request = customer.returnCar() self.assertEqual(shop.returnCar(request), 0)
def read_customer(customers: CUSTOMERS, customer: int, created: str) -> None: """ Attempts to create a customer. Creation times with bad formatting are ignored. """ try: created_dt: dt.datetime = dt.datetime.strptime(created, "%Y-%m-%d %H:%M:%S") created_dt = dt.datetime.combine(created_dt.date(), created_dt.time(), dt.timezone.utc) except ValueError: #Don't import the line for a ValueError pass else: customers[customer] = Customer(created_dt)
def test_request_new_account(self): """ Tests when request for new account is made it is opened or not :return: Assertion of test fail or pass """ dest_customer = Customer("Tempcust") dest_customer.request_new_account("S") dest_customer.deposit(500) acnt_no = dest_customer.get_account_number() dest_customer.open_account(acnt_no) self.assertEqual(dest_customer.check_balance(), 500, msg=" New Account Not Opened")
def main(): CUSTOMER_FOLDERS = pd.read_csv(EXTRACT_PATH, delimiter='\t', encoding='latin1') community = {} with open("run_times.tab", "a") as f: writer = csv.writer(f, delimiter="\t", lineterminator="\n") #TODO: use apply or pipe rather than iterating over the dataframe for idx, row in CUSTOMER_FOLDERS.iterrows(): community[row['GPID']] = Customer( row['GPID'], row['CustomerFolder'], ROOT_PATH + row['CustomerFolder'] + '\\') community[row['GPID']].init_review_history() writer.writerows(community[row['GPID']].log)
def test_pay_physic_and_digital_products(self): initial_wallet = 500 customer = Customer(name='macabeus', wallet=initial_wallet) order_two_products = Order(products=[physic_product, digital_product], customer=customer) order_two_products.pay() assert customer.wallet == \ initial_wallet - physic_product.price - digital_product.price, \ 'Should cash the wallet' assert customer.email_messages[0] == 'discount voucher R$ 10', \ 'Should receive a voucher because purchased a digital product'
def main(): cust1 = Customer() cust1.name = 'Heart of Gold' cust1.address = 'The Milky Way Galaxy' cust1.enterprise = False cust2 = Customer() cust2.name = 'Milliways Restaurant' cust2.address = 'Magrathea' cust2.enterprise = True ord1 = Order() ord1.orderid = 1 ord1.customer = cust1 ord1.expedited = False ord1.shipping_address = 'Infinitely Improbable' ord2 = (Order()) ord2.orderid = 2 ord2.customer = cust2 ord2.expedited = True ord2.shipping_address = 'Magrathea' Order.orders = [ord1, ord2] for name in ord1.get_expedited_orders_customer_names(): print(name) for address in ord1.get_expedited_orders_customer_addresses(): print(address) for address in ord1.get_expedited_orders_shipping_addresses(): print(address) # for name in ord1.get_expedited_orders_customer_names(Order.orders): # print(name) # for address in ord1.get_expedited_orders_customer_addresses(Order.orders): # print(address) # for address in ord1.get_expedited_orders_shipping_addresses(Order.orders): # print(address) Order.set_order_expedited(1, Order.orders)
def load_bank_data(self): customer_1 = Customer("Adam", "1234", ["14", "Wilcot Street", "Bath", "B5 5RT"]) account_no = 1234 account_1 = Account(5000.00, account_no) customer_1.open_account(account_1) self.customers_list.append(customer_1) customer_2 = Customer("David", "password", ["60", "Holborn Viaduct", "London", "EC1A 2FD"]) account_no += 1 account_2 = Account(3200.00, account_no) customer_2.open_account(account_2) self.customers_list.append(customer_2) customer_3 = Customer("Alice", "MoonLight", ["5", "Cardigan Street", "Birmingham", "B4 7BD"]) account_no += 1 account_3 = Account(18000.00, account_no) customer_3.open_account(account_3) self.customers_list.append(customer_3) customer_4 = Customer( "Ali", "150A", ["44", "Churchill Way West", "Basingstoke", "RG21 6YR"]) account_no += 1 account_4 = Account(40.00, account_no) customer_4.open_account(account_4) self.customers_list.append(customer_4) admin_1 = Admin("Jake", "1441", True, ["12", "London Road", "Birmingham", "B95 7TT"]) self.admins_list.append(admin_1) admin_2 = Admin("Stish", "2222", False, ["47", "Mars Street", "Newcastle", "NE12 6TZ"]) self.admins_list.append(admin_2)
def main(): shop = BikeRental(100) customer = Customer() while True: print(""" ====== Bike Rental Shop ======= 1. Display available bikes 2. Request a bike on hourly basis $5 3. Request a bike on daily basis $20 4. Request a bike on weekly basis $60 5. Return a bike 6. Exit """) choice = input("Enter your choice ? ") try: choice = int(choice) except ValueError: print("That's not an integer value you entered !") continue if choice == 1: shop.displayStock() elif choice == 2: customer.rentalTime = shop.rentBikesOnHourlyBasis( customer.requestBike()) customer.rentalBasics = 1 elif choice == 3: customer.rentalBasics = 2 customer.rentalTime = shop.rentBikesOnDailyBasis( customer.requestBike()) elif choice == 4: customer.rentalBasics = 3 customer.rentalTime = shop.rentBikesOnWeeklyBasis( customer.requestBike()) elif choice == 5: customer.bill = shop.returnBikes(customer.returnBike()) customer.rentalBasics, customer.rentalTime, customer.bikes = 0, 0, 0 elif choice == 6: break else: print("INVALID Choice")
def matcher(buyerPref, sellerPref): matchBuyer = {} matchSeller = {} #set up buyers and sellers for buyer in buyerPref.keys(): matchBuyer[buyer] = Customer(buyerPref[buyer]) for seller in sellerPref.keys(): matchSeller[seller] = Vendor(sellerPref[seller]) for seller in matchSeller.keys(): nowSeller = matchSeller[seller] counter = 1 while not nowSeller.matched: for cust in nowSeller.prefs: nowSeller.visited.append(cust) nowCust = matchBuyer[cust] if not nowCust.full: nowCust.addMatch(seller) nowSeller.addMatch(cust) elif nowCust.full: if nowCust.isPref(seller): if nowCust.full: delSeller = nowCust.removeNonPref() matchSeller[delSeller].removeMatch() nowCust.addMatch(seller) nowSeller.removeMatch() nowSeller.addMatch(cust) else: break #now look through other buyers for cust in matchBuyer.keys(): nowCust = matchBuyer[cust] if cust not in nowSeller.visited: if not nowCust.full: nowCust.addMatch(seller) former = nowSeller.removeMatch(self) matchBuyer[former].removeMatch(seller) nowSeller.addMatch(cust) #print results for k in matchBuyer.keys(): matchBuyer[k].seeAttr for k in matchSeller.keys(): matchSeller[k].seeAttr
def lambda_handler(event, context): #interface handler. try: #response_object. response_obj = Response() #Extract and validate the collection containing the customer data. customer_data = event.get("data") is_valid = response_obj.request_parser(customer_data) #Exit_point: failure, no data to process. if not is_valid: return response_obj.error_response("data", "path", "data empty", "no customer data to pocss", 404, "client error", "", "in_valid customer data") #customer object. cust_obj = Customer() #Iterate over all the customer data. for curr_customer in customer_data: #check_validity. isCustomerValid = cust_obj.check_validity(curr_customer) #build Invalid customer list. if not isCustomerValid: # add the inValid customer to the inValidCustomerList. cust_obj.add_invalid_list(curr_customer) #build unique_id. unique_cus_id = cust_obj.build_unique_id(curr_customer) #build the duplicate list. cust_obj.validate_duplicate_customer(curr_customer, unique_cus_id) #build the in_valid set. inValid_customers = cust_obj.merge_inVaid_duplicate_customer_set() #print the invalid customers. for customer in inValid_customers: print(customer) return response_obj.success_response(200, "invalid_customers_marked") except: traceback.print_exc() return response_obj.exception_response( "invalid_data in the request payload")
def run_simulation(self): """The central method called in main.py.""" customer = Customer() soda_machine = SodaMachine() will_proceed = True while will_proceed: user_option = user_interface.simulation_main_menu() if user_option == 1: soda_machine.begin_transaction(customer) elif user_option == 2: customer.check_coins_in_wallet() elif user_option == 3: customer.check_backpack() else: will_proceed = False