예제 #1
0
파일: main.py 프로젝트: bobbyesh/forecaster
def get_tables():
    years = 3
    start_month = Month(4, 2018)
    end_month = Month(4, start_month.year + years)

    # Init total savings
    current_total = 0
    initial_savings = 1000

    # Init current time
    current_time = Month(4, 2018)

    # Initialize income and expenses
    income = get_income(current_time)
    expenses = get_expenses(current_time)

    months = []
    expenses_list = []
    incomes = []
    nets = []
    savings = []

    # Accumulate savings
    while expenses.month < end_month:
        monthly_net = income.monthly() - expenses.monthly()
        current_total += monthly_net

        months.append(expenses.month)
        expenses_list.append(expenses.monthly())
        incomes.append(income.monthly())
        nets.append(monthly_net)

        if savings:
            temp = savings[-1] + monthly_net
        else:
            temp = initial_savings

        savings.append(temp)

        expenses.increment_month()
        income.increment_month()

    month_chunks = list(as_months(months))
    expenses_chunks = list(as_months(expenses_list))
    income_chunks = list(as_months(incomes))
    net_chunks = list(as_months(nets))
    savings_chunks = list(as_months(savings))

    tables = []
    for m, e, i, n, s in zip(month_chunks, expenses_chunks, income_chunks,
                             net_chunks, savings_chunks):
        t = [['Month'] + m, ['Expenses'] + e, ['Income'] + i, ['Net'] + n,
             ['Savings'] + s]
        tables.append(t)

    return tables

    print("By {} your savings will be {}".format(expenses.month,
                                                 current_total))
예제 #2
0
 def test_from_date_and_strftime(self):
     python2_eol = Month.from_date(date(2020, 1, 1))
     self.assertEqual(python2_eol, Month(2020, 1))
     leap_month = Month.from_date(date(2000, 2, 29))
     self.assertEqual(leap_month, Month(2000, 2))
     self.assertEqual(python2_eol.strftime('%Y-%m'), "2020-01")
     with set_locale('C'):
         self.assertEqual(leap_month.strftime('%b %Y'), "Feb 2000")
         self.assertEqual(python2_eol.strftime('%b %Y'), "Jan 2020")
예제 #3
0
 def to_python(self, value):
     if isinstance(value, Month):
         month = value
     elif isinstance(value, datetime.date):
         month = Month.from_date(value)
     elif isinstance(value, basestring):
         month = Month.from_string(value)
     else:
         month = None
     return month
예제 #4
0
 def to_python(self, value):
     if isinstance(value, Month):
         month = value
     elif isinstance(value, datetime.date):
         month = Month.from_date(value)
     elif isinstance(value, basestring):
         month = Month.from_string(value)
     else:
         month = None
     return month
예제 #5
0
 def test_first_day_and_last_day(self):
     python2_eol = Month(2020, 1)
     pycon_2019 = Month(2019, 5)
     leap_month = Month(2000, 2)
     non_leap_month = Month(1900, 2)
     self.assertEqual(python2_eol.first_day, date(2020, 1, 1))
     self.assertEqual(python2_eol.last_day, date(2020, 1, 31))
     self.assertEqual(pycon_2019.first_day, date(2019, 5, 1))
     self.assertEqual(pycon_2019.last_day, date(2019, 5, 31))
     self.assertEqual(leap_month.last_day, date(2000, 2, 29))
     self.assertEqual(non_leap_month.last_day, date(1900, 2, 28))
예제 #6
0
    def newMonth(self, *args):
        if not args:
            print('ERROR in runtime.py!!! Month name must be entered.')
            return

        if len(args) > 1:
            print('ERROR in runtime.py!!! Too many agruments')
            return

        if self.currentMonth:
            self.monthHistory[self.currentMonth.name] = self.currentMonth

        self.currentMonth = Month(args[0])
예제 #7
0
파일: main.py 프로젝트: bobbyesh/forecaster
def get_income(current_time):
    changes = {
        0: {
            Month(2, 2019): 4350,
            Month(5, 2020): 7900,
        },
    }

    return Income(month=current_time,
                  initial_incomes={
                      0: 4050,
                      1: 1700
                  },
                  changes=changes)
예제 #8
0
    def run_to(self, date, include_month_end):
        """Output all days before this date"""
        if self.date == date:
            return
        if self.month is None:
            if self.is_last_month():
                return
            self.month = Month.for_date(date)
            self.consumer.start_month(self.month)
            self.months_started += 1

        while self.date is None or self.date < (date -
                                                datetime.timedelta(days=1)):
            for d in self.month.days():
                if self.date is not None and d <= self.date:
                    continue
                if d == date:
                    break
                self.consumer.start_day(d)
                self.date = d
            else:
                if not include_month_end and self.month.next().first_day(
                ) == date:
                    return
                self.consumer.end_month(self.month)
                if self.is_last_month():
                    self.month = None
                    return
                self.month = self.month.next()
                self.consumer.start_month(self.month)
                self.months_started += 1
예제 #9
0
    def request_freeze_cancel(self, request, month=None):
        intern = request.user
        month = Month.from_int(int(month))
        current_freeze = intern.freezes.current_for_month(month)

        if not current_freeze:
            raise ObjectDoesNotExist("This month has no freeze to cancel.")

        if intern.freeze_cancel_requests.current_for_month(month):
            raise PermissionDenied("There is a pending freeze cancel request for this month already.")

        # TODO: Check that there are no rotations, leaves, freezes, or related requests in the month to be disabled

        cancel_request = FreezeCancelRequest.objects.create(
            intern=intern,
            month=month,
        )

        # --notifications--

        # Subscribe user to receive update notifications on the request
        subscribe(request.user.settings_set.first(), "freeze_cancel_request_approved", object_id=cancel_request.id)
        subscribe(request.user.settings_set.first(), "freeze_cancel_request_declined", object_id=cancel_request.id)

        # Notify medical internship unit of the request
        notify(
            "A freeze cancellation request has been submitted by %s" % (request.user.profile.get_en_full_name()),
            "freeze_cancel_request_submitted",
            url="/planner/%d/" % cancel_request.intern.profile.intern.internship.id,
            )

        messages.success(request._request, "Your freeze cancellation request has been submitted successfully.")

        return Response(status=HTTP_201_CREATED)
예제 #10
0
    def request_freeze(self, request, month=None):
        if request.method == "POST":
            month = Month.from_int(int(month))
            intern = self.request.user

            # TODO: Check that month is not frozen or disabled or there is a freeze request
            # TODO: Check that month has not current rotation or rotation request

            form = FreezeRequestForm(data=request.data, instance=FreezeRequest(intern=intern, month=month))

            if form.is_valid():

                freeze_request = form.save()

                # Subscribe user to receive update notifications on the request
                subscribe(intern.settings_set.first(), "freeze_request_approved", object_id=freeze_request.id)
                subscribe(intern.settings_set.first(), "freeze_request_declined", object_id=freeze_request.id)

                # Notify medical internship unit of the request
                notify(
                    "A new freeze request has been submitted by %s" % (request.user.profile.get_en_full_name()),
                    "freeze_request_submitted",
                    url="/planner/%d/" % freeze_request.intern.profile.intern.internship.id,
                )

                # Display success message to user
                messages.success(request._request, "Your freeze request has been submitted successfully.")

            response_data = {'errors': form.errors}
            return Response(response_data)
        return FreezeRequestFormView.as_view()(request._request, month)
예제 #11
0
def test():
    changes = {
        Month(2, 2019): 4350,
        Month(5, 2020): 7900,
    }

    income = Income(month=START_MONTH,
                    initial_incomes={
                        0: 4050,
                        1: 1700
                    },
                    changes={0: changes})
    for _ in range(40):
        income.increment_month()
        print('month', income.month)
        print(income.monthly())
예제 #12
0
    def monthly_list(self, request, pk, *args, **kwargs):
        """
        Return the list of rotations for a given month and department
        """
        batch = get_object_or_404(Batch, id=pk)

        if len(request.query_params.keys()) == 0:
            raise ParseError(detail="No query parameters were specified.")  # FIXME: Is this the most accurate error?

        department = request.query_params.get('department')
        month = request.query_params.get('month')

        if department is None or month is None:
            raise ParseError(detail="Both `department` and `month` query parameters should be specified.")

        month = Month.from_int(int(month))
        department = Department.objects.get(id=department)
        rotations = Rotation.objects.filter(
            internship__intern__batch=batch,
            department=department,
            month=month,
        ).prefetch_related(
            'internship__intern__profile',
        ).order_by(
            Lower('internship__intern__profile__en_first_name'),
            Lower('internship__intern__profile__en_father_name'),
            Lower('internship__intern__profile__en_grandfather_name'),
            Lower('internship__intern__profile__en_last_name'),
        )

        if request.query_params.get('excel'):
            return excel_file_as_http_response(batch, department, month, rotations)

        serialized = FullRotationSerializer(rotations, many=True)
        return Response(serialized.data)
예제 #13
0
 def __init__(self, year_no):
     '''initialise year number (last two digits of year), and month dict (empty of weather data)'''
     self.year_no = year_no
     self.months = {}
     for month_string in MONTHLIST:
         month_object = Month(month_string, self.year_no)
         self.months[month_string] = month_object
예제 #14
0
def run(*args):
    reservoirs = Reservoir.objects.all()

    for reservoir in reservoirs:

        i = 1

        for h in range(random.randint(25, 30)):
            home = Home(
                reservoir=reservoir,
                home_name=f"Home {i}",
                number_of_residents=random.randint(1, 7),
            )

            print(home)

            home.save()

            for year in year_list:
                for month in months_list:
                    if year == currentYear and month > currentMonth:
                        break

                    home_water_consumption = HomeWaterConsumption(
                        home=home,
                        date=Month(year, month),
                        water_consumption=random.randint(500, 1500),
                    )

                    print(home_water_consumption)

                    home_water_consumption.save()

            i += 1
예제 #15
0
 def to_python(self, value):
     if isinstance(value, Month):
         month = value
     elif isinstance(value, datetime.date):
         month = Month.from_date(value)
         if len(str(month.year)) < 4:
             raise exceptions.ValidationError(
                 self.error_messages['invalid_year'],
                 code='invalid_year',
                 params={'value': value},
             )
     elif isinstance(value, string_type):
         month = Month.from_string(value)
     else:
         month = None
     return month
예제 #16
0
 def __init__(self, year):
     """
         Une representation d'un calendrier
         :param year: l'année du calendrier
     """
     self.year = year
     self.months = [Month(x, year) for x in range(1, 13)]
예제 #17
0
 def test_ordering(self):
     python2_eol = Month(2020, 1)
     pycon_2019 = Month(2019, 5)
     self.assertLess(pycon_2019, python2_eol)
     self.assertGreater(python2_eol, pycon_2019)
     self.assertLessEqual(pycon_2019, python2_eol)
     self.assertGreaterEqual(python2_eol, pycon_2019)
     self.assertFalse(pycon_2019 > python2_eol)
     self.assertFalse(pycon_2019 >= python2_eol)
     self.assertFalse(python2_eol < pycon_2019)
     self.assertFalse(python2_eol <= pycon_2019)
     with self.assertRaises(TypeError):
         python2_eol < (2021, 12)  # tuples aren't months
     with self.assertRaises(TypeError):
         python2_eol >= (2021, 12)  # tuples aren't months
     with self.assertRaises(TypeError):
         (2021, 12) < python2_eol  # tuples aren't months
예제 #18
0
    def validate(self, data):
        """
        Check that:
          (1) month has a rotation (?)
          (2) intern has enough remaining days of the selected leave type
          (3) start and end date are actually within the selected month
          (4) end date is after (or equal to) start date
        """
        intern = data['intern']
        internship = intern.profile.intern.internship

        leave_type = data['type']
        leave_setting = intern.leave_settings.get(type=leave_type)

        month = data['month']
        start_date = data['start_date']
        end_date = data['end_date']

        errors = []

        if not internship.rotations.current_for_month(month):
            errors.append("This month has no rotation.")

        leave_length = (end_date - start_date).days + 1
        remaining_days = leave_setting.remaining_days
        if leave_length > remaining_days:
            errors.append("You are requesting %d days of %s, but you only have %d days available." % (
                leave_length,
                leave_type.name.lower(),
                remaining_days,
            ))

        if Month.from_date(start_date) != month:
            errors.append("Start date should be within the selected month.")

        if Month.from_date(end_date) != month:
            errors.append("End date should be within the selected month.")

        if not end_date >= start_date:
            errors.append("End date should be after or equal to start date.")

        if errors:
            raise serializers.ValidationError(errors)

        return data
예제 #19
0
 def __init__(self, consumer, start_date=None, months=12):
     if start_date is None:
         start_date = datetime.date.today()
     start_month = Month.for_date(start_date)
     ms = MonthAdapter(PeriodMonthSplitter(consumer), start_month, months)
     super(MonthCalendarFacade,
           self).__init__(ms,
                          start=start_date,
                          end=start_month.add(months).first_day())
예제 #20
0
파일: year.py 프로젝트: xuyuan/open-timer
 def __init__(self, year):
     self.applicationList = []
     self.categoryList = []
     for i in range(1, 13):
         result = Month(year, i)
         self.applicationList = mergeAppDataList(self.applicationList,
                                                 result.applicationList)
     self.categoryList = updateCategory(self.applicationList)
     self.applicationList.sort()
     self.categoryList.sort()
     self.info = "%(year)d" % vars()
예제 #21
0
 def test_immutability(self):
     python2_eol = Month(2020, 1)
     with self.assertRaises(Exception):
         python2_eol.year = 2000
     with self.assertRaises(Exception):
         python2_eol.month = 1
     with self.assertRaises(Exception):
         del python2_eol.year
     with self.assertRaises(Exception):
         del python2_eol.month
     with self.assertRaises(Exception):
         python2_eol.__dict__
     self.assertEqual(hash(python2_eol), hash(Month(2020, 1)))
     self.assertNotEqual(hash(python2_eol), hash(Month(2020, 2)))
     self.assertNotEqual(hash(python2_eol), hash(Month(2019, 1)))
     self.assertNotEqual(hash(python2_eol), hash(Month(2019, 12)))
     self.assertNotEqual(hash(python2_eol), hash(Month(2019, 2)))
예제 #22
0
    def __init__(self):
        self.year = 2016
        self.months = []

        months = [
            ("January", 31),
            ("February", 30),
            ("March", 31),
            ("April", 30),
            ("May", 31),
            ("June", 30),
            ("July", 31),
            ("August", 31),
            ("September", 30),
            ("October", 31),
            ("November", 30),
            ("December", 31)]

        for mon in months:
            holder = Month(mon[0])
            holder.fill_month(mon[1])
            self.months.append(holder)
예제 #23
0
    def respond(self, request, department_id, month_id, list_type, *args, **kwargs):
        department = get_object_or_404(Department, id=department_id)
        month = Month.from_int(int(month_id))

        serialized = AcceptanceListSerializer(
            data=request.data,
            instance=AcceptanceList(department, month, list_type)
        )
        serialized.is_valid(raise_exception=True)
        acceptance_list = serialized.save()

        acceptance_list.respond_all()

        return Response(status=HTTP_200_OK)
예제 #24
0
파일: webapp.py 프로젝트: xuyuan/open-timer
def set_time():
    period = request.args.get('period')
    yy = int(request.args.get('yy'))
    mm = int(request.args.get('mm'))
    dd = int(request.args.get('dd'))
    global the_data
    if period == 'year':
        the_data = Year(yy)
    elif period == 'month':
        the_data = Month(yy, mm)
    elif period == 'week':
        the_data = Week(yy, mm, dd)
    else:
        the_data = Day(yy, mm, dd)
    return the_data.info
예제 #25
0
 def test_equality(self):
     python2_eol = Month(2020, 1)
     self.assertEqual(python2_eol, Month(2020, 1))
     self.assertNotEqual(python2_eol, Month(2020, 2))
     self.assertNotEqual(python2_eol, Month(2019, 1))
     self.assertFalse(python2_eol != Month(2020, 1))
     self.assertFalse(python2_eol == Month(2020, 2))
     self.assertNotEqual(python2_eol, date(2020, 1, 1))
     self.assertNotEqual(python2_eol, (2020, 1))
     self.assertNotEqual((2020, 1), python2_eol)  # tuples aren't months
예제 #26
0
    def with_specialty_details(self, request, month_id, specialty_id):
        month = Month.from_int(int(month_id))
        specialty = get_object_or_404(Specialty, id=specialty_id)
        hospitals = self.get_queryset().prefetch_related('departments')
        for hospital in hospitals:
            hospital.specialty_departments = \
                filter(lambda dep: dep.specialty == specialty, hospital.departments.all())

            for dep in hospital.specialty_departments:
                dep.acceptance_setting = AcceptanceSetting(
                    dep,
                    month,
                )

        serialized = ExtendedHospitalSerializer(hospitals, many=True)
        return Response(serialized.data)
예제 #27
0
def run(*args):
    reservoirs = Reservoir.objects.all()

    for reservoir in reservoirs:
        for year in year_list:
            for month in months_list:
                if year == currentYear and month > currentMonth:
                    break

                water_level = WaterLevel(reservoir=reservoir,
                                         date=Month(year, month),
                                         water_level=random.randint(
                                             30000, 50000),
                                         rainfall=random.randint(5, 25),
                                         temperature=random.randint(25, 47),
                                         evaporation=random.randint(2, 10))

                print(water_level)

                water_level.save()
예제 #28
0
def run(*args):
    reservoirs = Reservoir.objects.all()

    for reservoir in reservoirs:
        for year in year_list:
            for month in months_list:
                if year == currentYear and month > currentMonth:
                    break

                water_consumption_paddy = WaterConsumptionPaddy(
                    reservoir=reservoir,
                    date=Month(year, month),
                    water_consumption_paddy=random.randint(20000, 40000),
                    rainfall=random.randint(5, 25),
                    temperature=random.randint(25, 47),
                    evaporation=random.randint(2, 10))

                print(water_consumption_paddy)

                water_consumption_paddy.save()
def run(*args):
    reservoirs = Reservoir.objects.all()

    for reservoir in reservoirs:
        for year in year_list:
            for month in months_list:
                if year == currentYear and month > currentMonth:
                    break

                water_consumption_domestic = WaterConsumptionDomestic(
                    reservoir=reservoir,
                    date=Month(year, month),
                    water_consumption_domestic=random.randint(20000, 40000),
                    population=random.randint(5000, 20000),
                    no_of_families=random.randint(1000, 5000),
                    no_of_housing_units=random.randint(1000, 5000),
                )

                print(water_consumption_domestic)

                water_consumption_domestic.save()
예제 #30
0
    def upload(self, request):
        """ Upload Invoicing Report. """
        month = request.data.get('month', None)
        report = request.data.get('report', None)

        if not month or not report:
            return Response(
                {
                    'success': False,
                    'error': 'Month or report is not set.',
                }, 400)

        try:
            report = InvoicingReport.objects.get(month=month)
            report.report = request.data.get('report')
        except InvoicingReport.DoesNotExist:
            report = InvoicingReport(month=Month.from_string(month),
                                     report=request.data.get('report'))
        finally:
            report.save()

        return JsonResponse({'success': True})
예제 #31
0
    def cancel_rotation(self, request, month=None):
        internship = request.user.profile.intern.internship
        month = Month.from_int(int(month))
        current_rotation = internship.rotations.current_for_month(month)

        if not current_rotation:
            raise ObjectDoesNotExist("This month has no rotation to cancel.")

        if internship.rotation_requests.current_for_month(month):
            raise PermissionDenied("There is a pending rotation request for this month already.")

        requested_department = current_rotation.rotation_request.requested_department
        requested_department.id = None
        requested_department.save()

        rr = internship.rotation_requests.create(
            month=month,
            specialty=requested_department.department.specialty,
            requested_department=requested_department,
            is_delete=True,
        )

        # --notifications--

        # Subscribe user to receive update notifications on the request
        subscribe(request.user.settings_set.first(), "rotation_request_approved", object_id=rr.id)
        subscribe(request.user.settings_set.first(), "rotation_request_declined", object_id=rr.id)

        # Notify medical internship unit of the request
        notify(
            "A cancellation request has been submitted by %s" % (request.user.profile.get_en_full_name()),
            "rotation_request_submitted",
            url="/planner/%d/" % rr.internship.id,
            )  # FIXME: avoid sending a lot of simultaneous notifications

        messages.success(request._request, "Your cancellation request has been submitted successfully.")

        return Response(status=HTTP_201_CREATED)
	def test_number_of_days_february(self):
		cal = Month(2, 1995)
		self.assertEqual(28, cal.days_number())
예제 #33
0
 def setUp(self):
     self.month = Month.check_month("")
예제 #34
0
def gen_month_field():
    return Month.from_date(gen_date())
예제 #35
0
class Runtime:
    def __init__(self):
        self.defaultItemsTypesGroups = {
            'expenses': [
                ItemType('Rent', 'Wallet', 'UAH'),
                ItemType('Food', 'Wallet', 'UAH'),
                ItemType('Pocket money', 'Wallet', 'UAH'),
                ItemType('Travelling', 'Travelling', 'UAH')
            ],
            'incomes': [
                ItemType('Serhii', 'Wallet', 'UAH'),
                ItemType('Alona', 'Wallet', 'UAH')
            ],
            'liabilities': [
                ItemType('Wallet', '', 'UAH', 'USD', 'EUR'),
                ItemType('Travelling', '', 'UAH', 'USD', 'EUR'),
                ItemType('Deposit', '', 'UAH', 'USD', 'EUR')
            ]
        }
        self.currentMonth = None
        self.totalLiab = None
        self.monthHistory = None
        self.commands = {
            'new total': self.newTotal,
            'new month': self.newMonth,
            'input total': self.inputTotal,
            'input month': self.inputCurrent,
            'show total': self.showTotal,
            'show month': self.showCurrent,
            'add item': self.addItem,
            'show transactions': self.showTransactions
        }

    def run(self):
        self.initialize()
        try:
            self.communicate()
        finally:
            self.finish()

    def initialize(self):
        self.initBasicItemsTypesGroups()
        self.initTotalLiabs()
        self.initCurrentMonth()
        self.initMonthHistory()

    def initBasicItemsTypesGroups(self):
        try:
            with open('database/items_types_groups.pkl', 'rb') as fileDB:
                tmpBasicItemsTypes = pickle.load(fileDB)
        except EOFError:
            with open('database/items_types_groups.pkl', 'wb') as fileDB:
                pickle.dump(self.defaultItemsTypesGroups, fileDB)

    def initTotalLiabs(self):
        try:
            with open('database/total.pkl', 'rb') as fileDB:
                self.totalLiab = pickle.load(fileDB)
        except EOFError:
            try:
                self.totalLiab = Liabilities(
                    self.getItemsTypesGroup('liabilities'))
            except EOFError:
                print('ERROR!!! Items types groups are not set')
                return

    def initCurrentMonth(self):
        try:
            with open('database/current_month.pkl', 'rb') as fileDB:
                self.currentMonth = pickle.load(fileDB)
        except EOFError:
            print('Current month isn not set')

    def initMonthHistory(self):
        try:
            with open('database/month_history.pkl', 'rb') as fileDB:
                self.monthHistory = pickle.load(fileDB)
        except EOFError:
            self.monthHistory = {}

    def communicate(self):
        request = input('Enter the request ("q" - quit): ')
        while request != 'q':
            self.processRequest(request)
            request = input('Enter the record ("q" - quit): ')

    def processRequest(self, requestString):
        args = [arg.strip().casefold() for arg in requestString.split(',')]

        def func():
            if len(args) > 1:
                self.commands[args[0]](*args[1:])
            else:
                self.commands[args[0]]()

        try:
            f.execWithException(self.processRequest, func, KeyError, TypeError)
        except (KeyError, TypeError):
            return

    def newTotal(self):
        self.totalLiab = Liabilities(self.getItemsTypesGroup('liabilities'))

    def newMonth(self, *args):
        if not args:
            print('ERROR in runtime.py!!! Month name must be entered.')
            return

        if len(args) > 1:
            print('ERROR in runtime.py!!! Too many agruments')
            return

        if self.currentMonth:
            self.monthHistory[self.currentMonth.name] = self.currentMonth

        self.currentMonth = Month(args[0])

    def inputTotal(self, *args):
        def func():
            item = args[0]
            amount = Runtime.reduceAmount(args[1])
            if len(args) == 2:
                currency = 'uah'
            else:
                currency = args[2]

            self.totalLiab.changeItemAmount(item, amount, currency)

        try:
            f.execWithException(self.inputTotal, func, ValueError, KeyError,
                                IndexError)
        except (ValueError, KeyError, IndexError):
            return

    def inputCurrent(self, *args):
        if not self.currentMonth:
            print('"Current Month" record must be created before filling in.')
            return

        def func():
            itemsGroupName = args[0]
            itemName = args[1]
            amount = Runtime.reduceAmount(args[2])
            if len(args) == 3:
                currency = 'uah'
            else:
                currency = args[3]

            itemsGroup = self.currentMonth.getItemsGroup(itemsGroupName)
            itemsGroup.changeItemAmount(itemName, amount, currency)
            itemCorrespondItem = itemsGroup.getItemCorrespondItem(itemName)

            if itemCorrespondItem and itemsGroupName.casefold(
            ) != 'liabilities':
                if itemsGroupName.casefold() == 'expenses':
                    amount *= -1
                itemsGroupLiab = self.currentMonth.getItemsGroup('liabilities')
                itemsGroupLiab.changeItemAmount(itemCorrespondItem, amount,
                                                currency)
                self.totalLiab.changeItemAmount(itemCorrespondItem, amount,
                                                currency)

            if itemsGroupName.casefold() == 'liabilities':
                self.totalLiab.changeItemAmount(itemName, amount, currency)

            if len(args) == 3:
                self.logTransaction(*args, currency)
            else:
                self.logTransaction(*args)

        try:
            f.execWithException(self.inputCurrent, func, ValueError,
                                IndexError, KeyError)
        except (ValueError, IndexError, KeyError):
            return

    def showTotal(self):
        if self.totalLiab:
            print(self.totalLiab)
        else:
            print('"Total Savings" record must be created before being shown.')

    def showCurrent(self):
        if self.currentMonth:
            print(self.currentMonth)
        else:
            print('"Current Month" record must be created before being shown.')

    def getItemsTypesGroup(self, itemsTypesGroupName):
        try:
            with open('database/items_types_groups.pkl', 'rb') as fileDB:
                itemsTypesGroups = pickle.load(fileDB)
        except EOFError:
            print('ERROR!!! Items types groups are not set')
        else:
            return itemsTypesGroups[itemsTypesGroupName.casefold()]

    def addItem(self):
        pass

    def finish(self):
        with open('database/total.pkl', 'wb') as fileDB:
            pickle.dump(self.totalLiab, fileDB)
        with open('database/current_month.pkl', 'wb') as fileDB:
            pickle.dump(self.currentMonth, fileDB)
        with open('database/month_history.pkl', 'wb') as fileDB:
            pickle.dump(self.monthHistory, fileDB)

    @staticmethod
    def reduceAmount(amountString):
        return reduce(lambda x, y: x + y,
                      map(lambda x: float(x), amountString.split()), 0)

    def logTransaction(self, *args):
        with open('database/transactions.txt', 'a') as file:
            file.write('{0:18} | {1:18} | '.format(
                datetime.today().strftime('%Y %B "%d"'),
                self.currentMonth.name.capitalize()))
            for arg in args:
                file.write('{0:15} | '.format(arg))
            file.write('\n')

    def showTransactions(self):
        with open('database/transactions.txt') as file:
            for line in file:
                print(line.strip())
예제 #36
0
 def get_display_starting_month(self, request):
     return Response({'id': int(Month.from_date(datetime(timezone.now().year, 1, 1)))})
예제 #37
0
 def test_string_representations(self):
     python2_eol = Month(2020, 1)
     self.assertEqual(str(python2_eol), "2020-01")
     new_month = eval(repr(python2_eol))
     self.assertEqual(new_month.year, python2_eol.year)
     self.assertEqual(new_month.month, python2_eol.month)
예제 #38
0
 def test_bad1(self):
     self.month = Month.check_month("Juneuronfs")
     correct_month = 6
     self.assertEqual(correct_month, self.month)
예제 #39
0
            value *= (1 + HomeOwned.AVG_APPRECIATION)

        return value

    def balance(self):
        payments = self.payments_made()
        fv_original = (self.original_value - self.downpayment) * (
            (1 + self.interest)**payments)
        fv_annuity = self.mortgage * ((
            (1 + self.interest)**payments - 1) / self.interest)
        return fv_original - fv_annuity

    def payments_made(self):
        return (self.month - self.purchased_on).days / 30


class Rental(Housing):
    UTILITIES = 250
    INSURANCE = 33

    def __init__(self, rent, movein):
        super().__init__(movein)
        self.rent = rent

    def monthly(self):
        return self.rent + Rental.UTILITIES + Rental.INSURANCE


if __name__ == '__main__':
    r = Rental(rent=1050, movein=Month(9, 2018))
    print('rental monthly', r.monthly())
예제 #40
0
 def test_good5(self):
     self.month = Month.check_month("5")
     correct_month = 5
     self.assertEqual(correct_month, self.month)
예제 #41
0
 def test_good6(self):
     self.month = Month.check_month("December")
     correct_month = 12
     self.assertEqual(correct_month, self.month)
예제 #42
0
 def test_middle4(self):
     self.month = Month.check_month("Janurarily")
     correct_month = 1
     self.assertEqual(correct_month, self.month)
예제 #43
0
 def test_bad3(self):
     self.month = Month.check_month("0")
     correct_month = 1
     self.assertEqual(correct_month, self.month)
예제 #44
0
 def test_bad2(self):
     self.month = Month.check_month("14")
     correct_month = 12
     self.assertEqual(correct_month, self.month)
예제 #45
0
 def to_internal_value(self, data):
     return Month.from_int(int(data))
예제 #46
0
 def get_object(self):
     queryset = self.get_queryset()
     month = Month.from_int(int(self.kwargs[self.lookup_field]))
     return filter(lambda m: m.month == month, queryset)[0]
예제 #47
0
 def test_vgood7(self):
     self.month = Month.check_month("Fall")
     correct_month = 10
     self.assertEqual(correct_month, self.month)
	def test_header(self):
		cal = Month(5, 2012)
		result = cal.header()
		self.assertEqual("      May 2012", result)
예제 #49
0
from datetime import datetime
from month import Month

START_TIME = datetime(2018, 4, 1)
END_TIME = datetime(2020, 12, 1)

START_MONTH = Month(4, 2018)
END_MONTH_YEAR = Month.from_datetime(END_TIME)
	def test_number_of_days_non_leap_century(self):
		cal = Month(2, 1900)
		self.assertEqual(28, cal.days_number())
예제 #51
0
 def test_initializer(self):
     python2_eol = Month(2020, 1)
     self.assertEqual(python2_eol.year, 2020)
     self.assertEqual(python2_eol.month, 1)
예제 #52
0
    return payment(monthyear,
                   starting=Const.student,
                   payment=Payment.student,
                   increment=True)


def car(monthyear):
    return payment(monthyear,
                   starting=Const.car,
                   payment=Payment.car,
                   increment=False)


def ring(monthyear):
    return payment(monthyear,
                   starting=Const.ring,
                   payment=Payment.ring,
                   increment=False)


def debt(monthyear):
    """Return the debt for the month and year of :arg:`monthyear`"""
    return student(monthyear) + car(monthyear) + ring(monthyear)


if __name__ == '__main__':
    monthyear = Month.from_datetime(datetime(2018, 6, 1))
    for _ in range(13):
        print(debt(monthyear))
        monthyear = monthyear.next()
	def test_format_days(self):
		cal = Month(2, 1990)
		expected = ["  ","  ","  ","  "," 1"," 2"," 3"," 4"," 5"," 6"," 7"," 8"," 9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28"]
		self.assertEqual(expected, cal.format_days())
예제 #54
0
import sys
from month import Month
from year import Year

if len(sys.argv) == 1:
	cal = Month()
elif len(sys.argv) == 2:
	cal = Year(int(sys.argv[1]))
else:
	month = sys.argv[1]
	year = sys.argv[2]
	cal = Month(month, year)
print cal.display()
예제 #55
0
파일: tests.py 프로젝트: lgoldbach/parkour
 def setUp(self):
     self.now = datetime.now()
     self.report = InvoicingReport(
         month=Month(self.now.year, self.now.month),
         report=SimpleUploadedFile('file.txt', b'content'),
     )
	def test_number_of_days_leap_year(self):
		cal = Month(2, 1996)
		self.assertEqual(29, cal.days_number())
예제 #57
0
 def get_object(self):
     department = get_object_or_404(Department, id=self.kwargs['department_id'])
     month = Month.from_int(int(self.kwargs['month_id']))
     return AcceptanceSetting(department, month)
예제 #58
0
 def make_month(self, i):
     print "Making month:", i, "....",
     Month(self.year, i, self.images[i - 1], self.lang).make()
     print "Done"
예제 #59
0
 def test_vbad0(self):
     self.month = Month.check_month("eiotyhwrt345")
     correct_month = 1
     self.assertEqual(correct_month, self.month)
	def test_blank_spaces(self):
		cal = Month(2, 1990)
		self.assertEqual(["  ","  ","  ","  "], cal.spaces())