Пример #1
0
    def optimal_order_quantity(raw_costs, demand):
        """
        Calculate economic order quantity (optimal Q*) given raw costs and demand.

        Parameters
        ----------
        raw_costs : RawCosts
            A `RawCosts` object, containing a set of raw cost values
        demand : Demand
            A `Demand` object, containing demand quantity and time frame

        Returns
        -------
        optimal_order_quantity: float
        """

        Validate.required(raw_costs, "raw_costs")
        Validate.required(demand, "demand")

        # if holding cost is 0, optimal Q would be D (i.e.
        # minimize ordering cost with one order across all demand)
        if raw_costs.holding_cost == 0.0:
            return demand.quantity
        else:
            numerator = 2 * raw_costs.ordering_cost * demand.quantity
            denominator = raw_costs.holding_cost

            return math.sqrt(numerator / denominator)
Пример #2
0
def program():
    print(
        "Логин должен начинаться с буквы и состоять не менее чем из 4 символов и не более чем из 20 символов;\n"
        "при создании логина можно использовать латинские буквы, цифры, символы тире (-), подчеркивания (_) и точки (.)\n")

    user_login = input("Введите логин: " '\n')
    while Validate.validate_login(user_login) is None:
        print("Ошибка! Попробуйте еще раз")
        user_login = input("Введите логин: ")

    print("Пароль должен содержать не менее 8 символов\n")
    user_password = input("Введите пароль: ")
    while Validate.validate_password(user_password) is None:
        print("Ошибка! Попробуйте еще раз")
        user_password = input("Введите пароль: ")

    user = User(user_login, user_password, randint(1, 999999))

    print("login: "******"password: "******"id: " + str(user.uniq_id))

    user_data = ("login: "******"\npassword: "******"\nuniq_id: " + str(user.uniq_id))

    user_file = str(user.login) + "_" + str(randint(1, 999999)) + ".txt"
    s = open(user_file, 'w')
    s.write(str(user_data) + '\n')
    s.close()
    print("Файл '" + user_file + "' успешно сохранен")
Пример #3
0
    def shortage_cost(shortage_cost, shortage_quantity):
        """
        Calculate the shortage cost - the total cost of not having units in stock,
        including costs due to backorder, lost sales, lost customers, and operational
        disruptions.

        Parameters
        ----------
        shortage_cost : int or float
            Cost per unit of shortage, in dollars
        shortage_quantity : int
            The number of units of shortage, in units

        Returns
        -------
        shortage_cost : float
        """

        Validate.required(shortage_cost, "shortage_cost")
        Validate.non_negative(shortage_cost, "shortage_cost")

        Validate.required(shortage_quantity, "shortage_quantity")
        Validate.non_negative(shortage_quantity, "shortage_quantity")

        return shortage_cost * shortage_quantity
Пример #4
0
    def __validate__(x, a, b, c):
        # todo: revisit these: not always necessary
        # e.g. if x < a or > b, then pdf/cdf evaluate to 0 or 1
        for (var, name) in [(x, "x"), (a, "a"), (b, "b"), (c, "c")]:
            v.required(var, name)

        if a >= b:
            raise ValueError("a must be less than b")

        if c < a or c > b:
            raise ValueError("c must be between a and b")

        if x < a or x > b:
            raise ValueError("x must be between a and b")
Пример #5
0
    def total_cost(raw_costs, demand, order_quantity, expected_shortage=0):
        """
        Calculate total inventory cost - the combination of purchase,
        ordering, holding, and shortage cost components.

        Parameters
        ----------
        raw_costs : RawCosts
            A `RawCosts` object, containing a set of raw cost values
        demand : Demand
            A `Demand` object, containing demand quantity and time frame
        order_quantity : int
            The number of units purchased with each order
        expected_shortage : int, default 0
            The expected value of the number of units short

        Returns
        -------
        total_cost : float
        """

        Validate.required(raw_costs, "raw_costs")
        Validate.required(demand, "demand")
        Validate.required(order_quantity, "order_quantity")
        Validate.required(expected_shortage, "expected_shortage")

        return (
            Costs.purchase_cost(raw_costs.unit_cost, demand.quantity) +
            Costs.total_relevant_cost(raw_costs, demand, order_quantity) +
            Costs.shortage_cost(raw_costs.shortage_cost, expected_shortage))
Пример #6
0
    def optimal_cycle_time(raw_costs, demand):
        """
        Calculate optimal cycle time (T*) given raw costs and demand.

        Parameters
        ----------
        raw_costs : RawCosts
            A `RawCosts` object, containing a set of raw cost values
        demand : Demand
            A `Demand` object, containing demand quantity and time frame

        Returns
        -------
        optimal_cycle_time: float
        """

        Validate.required(raw_costs, "raw_costs")
        Validate.required(demand, "demand")
        Validate.positive(demand.quantity, "demand.quantity")
        Validate.positive(raw_costs.holding_cost, "raw_costs.holding_cost")

        numerator = 2 * raw_costs.ordering_cost
        denominator = demand.quantity * raw_costs.holding_cost

        return math.sqrt(numerator / denominator)
 def delete_donor(cursor):
     while True:
         try:
             cursor.execute("SELECT UniqueId FROM Donor;")
             data = cursor.fetchall()
             ids = [i[0] for i in data]
             print(ids, "(0) Cancel")
             user_input = input("Enter donor's ID or passport number: ").upper()
             if user_input == '0':
                 clear()
                 break
             elif not Validate.validate_id(user_input):
                 print("\n\tWrong ID or Passport number, enter a real value")
                 time.sleep(2)
                 clear()
                 continue
             elif user_input not in ids:
                 print("\n\tID is valid, but there is no entry with this ID yet.")
                 time.sleep(2)
                 clear()
                 continue
             else:
                 print("Deleting entry...")
                 cursor.execute("DELETE FROM Donor WHERE UniqueId = '{}';".format(user_input))
                 time.sleep(1)
             print("Done!")
             input()
             clear()
             break
         except Exception as e:
             print(e)
             print("\n\t! ! !  Belso Error ! ! ! ")
             input()
             clear()
Пример #8
0
 def update_progressbar(self, dt):
     """Updating progress bar and activating validation."""
     if self.progress != 100 and self.progress != -1:
         self.progress += 1
         self.status = 'Validating: {}%'.format(int(self.progress))
     elif self.progress == 100:
         check = Validate.ksvalidate(self.kstext)
         self.progress = -1
         self.status = check
Пример #9
0
    def optimal_relevant_cost(raw_costs, demand):
        """
        Calculate optimal relevant cost. (TRC(Q*))

        Parameters
        ----------
        raw_costs : RawCosts
            A `RawCosts` object, containing a set of raw cost values
        demand : Demand
            A `Demand` object, containing demand quantity and time frame

        Returns
        -------
        optimal_relevant_cost: float
        """

        Validate.required(raw_costs, "raw_costs")
        Validate.required(demand, "demand")

        return math.sqrt(2 * raw_costs.ordering_cost * raw_costs.holding_cost *
                         demand.quantity)
Пример #10
0
    def optimal_total_cost(raw_costs, demand):
        """
        Calculate optimal total cost. (TC(Q*))

        Parameters
        ----------
        raw_costs : RawCosts
            A `RawCosts` object, containing a set of raw cost values
        demand : Demand
            A `Demand` object, containing demand quantity and time frame

        Returns
        -------
        optimal_total_cost: float
        """

        Validate.required(raw_costs, "raw_costs")
        Validate.required(demand, "demand")

        return (raw_costs.unit_cost * demand.quantity +
                EOQ.optimal_relevant_cost(raw_costs=raw_costs, demand=demand))
Пример #11
0
    def total_relevant_cost(raw_costs, demand, order_quantity):
        """
        Calculate total inventory cost relevant to the calculation of economic order
        quantity.

        Note: The relevant cost components are those that change as a function of
        order quantity: ordering cost and holding cost.

        Parameters
        ----------
        raw_costs : RawCosts
            A `RawCosts` object, containing a set of raw cost values
        demand : Demand
            A `Demand` object, containing demand order_quantity and time frame
        order_quantity : int
            The number of units purchased with each order

        Returns
        -------
        total_relevant_cost : float
        """

        Validate.required(raw_costs, "raw_costs")
        Validate.required(demand, "demand")
        Validate.required(order_quantity, "order_quantity")

        return (Costs.ordering_cost(raw_costs.ordering_cost, demand.quantity,
                                    order_quantity) +
                Costs.holding_cost(raw_costs.holding_cost, order_quantity))
Пример #12
0
    def __init__(self, quantity, time_unit='Y'):
        Validate.required(quantity, "quantity")
        Validate.non_negative(quantity, "quantity")
        self.quantity = quantity

        Validate.one_of_allowable(time_unit, ['Y', 'M', 'W', 'D'], "time_unit")
        self.time_unit = time_unit
Пример #13
0
    def post(self):
        username = self.request.get("username")
        password = self.request.get("password")
        verify = self.request.get("verify")
        email = self.request.get("email")

        user = Validate(username, password, verify, email)

        username_error = ""
        password_error = ""
        verify_error = ""

        if user.validate():
            self.redirect("/welcome?username={0}".format(username))
        else:
            if not user.username_val():
                username_error = "That isn't a valid username."
            if not verify:
                verify_error = "Please verify your password."
            if password and verify:
                if not user.equal():
                    verify_error = "Passwords do not match."
                if not user.password_val():
                    password_error = "That isn't a valid password."

        self.write_form(username, username_error, password_error, verify_error,
                        email)
Пример #14
0
 def delete_donor():
     while True:
         try:
             with open("Data/donors.csv", "r") as f:
                 content = []
                 for line in f:
                     content.append(line.strip())
             ids = [
                 content[i].split(',')[6] for i in range(len(content))
                 if i != 0
             ]
             print(ids, "(0) Cancel")
             user_input = input(
                 "Enter donor's ID or passport number: ").upper()
             if user_input == '0':
                 clear()
                 break
             elif not Validate.validate_id(user_input):
                 print(
                     "\n\tWrong ID or Passport number, enter a real value")
                 time.sleep(2)
                 clear()
                 continue
             elif user_input not in ids:
                 print(
                     "\n\tID is valid, but there is no entry with this ID yet."
                 )
                 time.sleep(2)
                 clear()
                 continue
             else:
                 print("Deleting entry...")
                 with open("Data/donors.csv", "w") as f:
                     for line in content:
                         if user_input != line.split(",")[6]:
                             f.write(line + "\n")
                 time.sleep(1)
             print("Done!")
             input()
             clear()
             break
         except Exception as e:
             print(e)
             print("\n\t! ! !  Belso Error ! ! ! ")
             input()
             clear()
    def add_new_donation_event(cursor_object):
        print("Adding new event...\n")
        time.sleep(1)
        clear()
        e1 = Event()
        while True:
            e1.date_of_event = input("Date of Event: ")
            if Validate.validate_date(e1.date_of_event) and e1.registration_in_tendays():
                pass
            else:
                print("\n\t ! The registration should be at least 10 days from now. ! ")
                print("\t   ! Use this format to enter date: 'YYYY.MM.DD' ! \n")
                time.sleep(2)
                clear()
                continue

            e1.start_time = EventManagerDB.data_into_event_object(e1, Validate.validate_time, "Start Time: ", TIME_ERR)
            e1.end_time = EventManagerDB.data_into_event_object(e1, Validate.validate_time, "End Time: ", TIME_ERR)
            while not e1.is_starttime_before_endtime():
                print("\n\t ! The starting time should be before the ending time. ! ")
                time.sleep(2)
                clear()
                e1.end_time = ""
                e1.end_time = EventManagerDB.data_into_event_object(e1, Validate.validate_time, "End Time: ", TIME_ERR)

            e1.zip_code = EventManagerDB.data_into_event_object(e1, Validate.validate_zipcode, "ZIP code: ", ZIP_ERR)
            e1.city = EventManagerDB.data_into_event_object(e1, Validate.validate_city_name, "City: ", CITY_ERR)
            e1.address = EventManagerDB.data_into_event_object(e1, Validate.validate_address, "Address of event: ", ADDRESS_ERR)
            e1.available_beds = EventManagerDB.data_into_event_object(e1, Validate.validate_positive_int, "Available beds: ", POSINT_ERR)
            e1.planned_donor_number = EventManagerDB.data_into_event_object(e1, Validate.validate_positive_int, "Planned donor number: ", POSINT_ERR)

            e1.successfull = EventManagerDB.data_into_event_object(e1, Validate.validate_positive_int, "\n How many successfull donation was on the event?\n > ", POSINT_ERR)

            print("\nThe required functions: \n")

            print("Weekday :", e1.is_weekday())
            e1.duration = e1.calculate_duration()
            print("Duration: {} min  --  {} hours ".format(e1.duration, round(e1.duration/60, 1)))
            print("Maximum donor number:", e1.max_donor_number())
            print("Success rate: {}".format(e1.success_rate()))
            input("\n\n (Press ENTER to go BACK)")
            EventManagerDB.store_donation_data(e1, cursor_object)
            clear()
            break
 def delete_donor(cursor):
     while True:
         try:
             cursor.execute("SELECT UniqueId FROM Donor;")
             data = cursor.fetchall()
             ids = [i[0] for i in data]
             print(ids, "(0) Cancel")
             user_input = input(
                 "Enter donor's ID or passport number: ").upper()
             if user_input == '0':
                 clear()
                 break
             elif not Validate.validate_id(user_input):
                 print(
                     "\n\tWrong ID or Passport number, enter a real value")
                 time.sleep(2)
                 clear()
                 continue
             elif user_input not in ids:
                 print(
                     "\n\tID is valid, but there is no entry with this ID yet."
                 )
                 time.sleep(2)
                 clear()
                 continue
             else:
                 print("Deleting entry...")
                 cursor.execute(
                     "DELETE FROM Donor WHERE UniqueId = '{}';".format(
                         user_input))
                 time.sleep(1)
             print("Done!")
             input()
             clear()
             break
         except Exception as e:
             print(e)
             print("\n\t! ! !  Belso Error ! ! ! ")
             input()
             clear()
 def delete_donor():
     while True:
         try:
             with open("Data/donors.csv", "r") as f:
                 content = []
                 for line in f:
                     content.append(line.strip())
             ids = [content[i].split(",")[6] for i in range(len(content)) if i != 0]
             print(ids, "(0) Cancel")
             user_input = input("Enter donor's ID or passport number: ").upper()
             if user_input == "0":
                 clear()
                 break
             elif not Validate.validate_id(user_input):
                 print("\n\tWrong ID or Passport number, enter a real value")
                 time.sleep(2)
                 clear()
                 continue
             elif user_input not in ids:
                 print("\n\tID is valid, but there is no entry with this ID yet.")
                 time.sleep(2)
                 clear()
                 continue
             else:
                 print("Deleting entry...")
                 with open("Data/donors.csv", "w") as f:
                     for line in content:
                         if user_input != line.split(",")[6]:
                             f.write(line + "\n")
                 time.sleep(1)
             print("Done!")
             input()
             clear()
             break
         except Exception as e:
             print(e)
             print("\n\t! ! !  Belso Error ! ! ! ")
             input()
             clear()
Пример #18
0
    def purchase_cost(unit_cost, demand_quantity):
        """
        Calculate the purchase cost - the total landed cost for acquiring
        product needed to satisfy a given amount of demand.

        Parameters
        ----------
        unit_cost : int or float
            Cost per unit, in dollars
        demand_quantity : int
            The amount of demand, in units

        Returns
        -------
        purchase_cost: float
        """

        Validate.required(unit_cost, "unit_cost")
        Validate.non_negative(unit_cost, "unit_cost")

        Validate.required(demand_quantity, "demand_quantity")
        Validate.non_negative(demand_quantity, "demand_quantity")

        return unit_cost * demand_quantity
Пример #19
0
    def holding_cost(holding_cost, order_quantity):
        """
        Calculate the holding cost - the total cost of holding excess inventory,
        including storage, service costs, risk costs, and capital costs.

        Parameters
        ----------
        holding_cost : int or float
            Cost per unit of inventory per time period, in dollars
        order_quantity : int
            The number of units purchased per order, in units

        Returns
        -------
        holding_cost: float
        """

        Validate.required(holding_cost, "holding_cost")
        Validate.non_negative(holding_cost, "holding_cost")

        Validate.required(order_quantity, "order_quantity")
        Validate.non_negative(order_quantity, "order_quantity")

        return holding_cost * (order_quantity / 2)
Пример #20
0
    def insertData(self):
        username = self.name_lineEdit.text()

        password = self.password_lineEdit.text()

        if (not username) or (not password):
            msg = QMessageBox.information(self, 'Внимание!',
                                          'Вы не заполнили все поля.')
            return

        if Validate.validate_login(
                username) is None and Validate.validate_password(
                    password) is None:
            msg = QMessageBox.information(
                self, 'Внимание!', 'И логин и пароль введены неправильно')
            return

        if Validate.validate_login(username) is None:
            msg = QMessageBox.information(self, 'Внимание!',
                                          'Такой логин задать нельзя')
            return

        if Validate.validate_password(password) is None:
            msg = QMessageBox.information(self, 'Внимание!',
                                          'Такой пароль задать нельзя')
            return

        if Validate.validate_login(username) and Validate.validate_password(
                password):
            user = User(username, password, randint(1, 999999))

            spi = {
                'username': user.login,
                'password': user.password,
                'id': user.uniq_id
            }
            with open("all_users.json", 'a+') as file:
                json.dump(spi, file)

            msg = QMessageBox.information(self, 'Успех', str(spi))
            return
 def test_nothing(self):
     self.assertFalse(Validate.validate_email(""))
 def test_null(self):
     self.assertFalse(Validate.validate_blood_type("0"))
 def test_time_too_much_min(self):
     self.assertFalse(Validate.validate_time('15:60'))
 def test_time_too_much_hour(self):
     self.assertFalse(Validate.validate_time('25:30'))
 def test_time_valid(self):
     self.assertTrue(Validate.validate_time('12:35'))
 def test_time_nothing(self):
     self.assertFalse(Validate.validate_time(''))
 def test_azavarosupper(self):
     self.assertTrue(Validate.validate_city_name("SZERENCS"))
 def test_string(self):
     self.assertFalse(Validate.validate_positive_int("hsvee"))
 def test_nothing(self):
     self.assertFalse(Validate.validate_blood_type(""))
 def test_azavaroslower(self):
     self.assertTrue(Validate.validate_city_name("miskolc"))
 def test_mukodo(self):
     self.assertTrue(Validate.validate_date("1991.02.10"))
 def test_a(self):
     self.assertFalse(Validate.validate_blood_type("A"))
 def test_ofalse(self):
     self.assertFalse(Validate.validate_blood_type("O+"))
 def test_nuber(self):
     self.assertFalse(Validate.validate_positive_int("-15"))
 def test_longstring(self):
     self.assertFalse(Validate.validate_city_name("gegwv_svsv"))
 def init_class(self):
     """ This function receives the input data from users. """
     while len(self.input) < 5:
         self.input.append(Validate().validate_values(' Digite um número: ',
                                                      zero=True))
 def test_number(self):
     self.assertFalse(Validate.validate_city_name("29"))
 def test_positive(self):
     self.assertTrue(Validate.validate_positive_int("42"))
 def init_class(self):
     """ This function receives the input data from users. """
     while len(self.list) < 2:
         self.list.append(Validate().validate_strings(self.title, 2))
Пример #40
0
    def ordering_cost(ordering_cost, demand_quantity, order_quantity):
        """
        Calculate the ordering cost - the total cost of placing, receiving,
        and processing orders needed to fulfill a given amount of demand.

        Parameters
        ----------
        ordering_cost : int or float
            Cost per order, in dollars
        demand_quantity : int
            The amount of demand, in units
        order_quantity : int
            The number of units purchased per order, in units

        Returns
        -------
        ordering_cost: float
        """

        Validate.required(ordering_cost, "ordering_cost")
        Validate.non_negative(ordering_cost, "ordering_cost")

        Validate.required(demand_quantity, "demand_quantity")
        Validate.non_negative(demand_quantity, "demand_quantity")

        Validate.required(order_quantity, "order_quantity")
        Validate.positive(order_quantity, "order_quantity")

        return ordering_cost * (demand_quantity / order_quantity)
 def test_abminusupper(self):
     self.assertTrue(Validate.validate_blood_type("AB-"))
 def test_time_wrong_divider(self):
     self.assertFalse(Validate.validate_time('15.40'))
 def test_bpluslower(self):
     self.assertTrue(Validate.validate_blood_type("b+"))
 elif user_input == MENU_ITEM_7:
     user_input = ""
     while user_input == "":
         user_input = input("(0) Cancel\nType ID number: ")
         user_input = user_input.upper()
         clear()
         if user_input == '0':
             break
         elif user_input.isdigit():
             if connect_decider:
                 EventManagerDB.change_event(user_input, cursor)
                 connection.commit()
             else:
                 EventManagerCSV.change_event(user_input)
             actv_selection = 0
         elif Validate.validate_id(user_input):
             if connect_decider:
                 DonorManagerDB.change_donor_data(user_input,cursor)
                 connection.commit()
             else:
                 DonorManager.change_donor_data(user_input)
             actv_selection = 0
         else:
             print(ID_ERR + "\n\t\t\t\tor\n" + POSINT_ERR)
             time.sleep(3)
             clear()
             user_input = ""
 #
 # EXIT
 #
 elif user_input == MENU_ITEM_8:
 def test_nothing(self):
     self.assertFalse(Validate.validate_positive_int(""))
 def test_time_too_many_char(self):
     self.assertFalse(Validate.validate_time('005:30'))
 def test_null(self):
     self.assertFalse(Validate.validate_positive_int("0"))
 def test_long(self):
     self.assertFalse(Validate.validate_blood_type("ggsiiuh sv448hg hsuh94"))
 def test_oplus(self):
     self.assertTrue(Validate.validate_blood_type("0+"))