Best Python code snippet using avocado_python
comparison.py
Source:comparison.py  
1from math import copysign2from odoo import _3from odoo.tools.float_utils import float_is_zero4from .abstract import AbstractBuilder5class ComparisonBuilder(AbstractBuilder):6    # OVERRIDES7    def _get_params(self, period_ids: list, options: dict, line_id: str = None) -> dict:8        chart_ids = self.env['consolidation.chart'].search([('period_ids', 'in', period_ids)]).ids9        cols_amount = len(period_ids)10        include_percentage = cols_amount == 211        params = super()._get_params(period_ids, options, line_id)12        params.update({13            'chart_ids': chart_ids,14            'cols_amount': cols_amount,15            'include_percentage': include_percentage,16        })17        return params18    def _output_will_be_empty(self, period_ids: list, options: dict, line_id: str = None) -> bool:19        return len(period_ids) == 020    def _compute_account_totals(self, account_id: int, **kwargs) -> list:21        domain = [22            ('account_id', '=', account_id),23            ('period_id', 'in', kwargs.get('period_ids', []))24        ]25        groupby = ('period_id',)26        total_lines = self.env['consolidation.journal.line'].read_group(domain, ('total:sum(amount)',), groupby)27        if len(total_lines) == 0:28            return []29        totals = []30        total_dict = {line['period_id'][0]: line['total'] for line in total_lines}31        # Need to keep the order of periods as nothing in DB can order them32        for period_id in kwargs.get('period_ids', []):33            append_amount = total_dict.get(period_id, 0.0)34            totals.append(append_amount)35        return totals36    def _get_default_line_totals(self, options: dict, **kwargs) -> list:37        return kwargs.get('cols_amount', len(kwargs.get('period_ids', []))) * [0.0]38    def _format_account_line(self, account, level: int, totals: list, options: dict, **kwargs) -> dict:39        account_line = super()._format_account_line(account, level, totals, options, **kwargs)40        if kwargs.get('include_percentage', False) and totals and account_line:41            account_line['columns'].append(self._build_percentage_column(*totals))42        return account_line43    def _build_section_line(self, section, level: int, options: dict, **kwargs):44        section_totals, section_lines = super()._build_section_line(section, level, options, **kwargs)45        if kwargs.get('include_percentage', False) and section_totals and section_lines:46            section_lines[0]['columns'].append(self._build_percentage_column(*section_totals))47        return section_totals, section_lines48    def _build_total_line(self, totals: list, options: dict, **kwargs) -> dict:49        total_line = super()._build_total_line(totals, options, **kwargs)50        if kwargs.get('include_percentage', False) and total_line and totals:51            total_line['columns'].append(self._build_percentage_column(*totals))52        return total_line53    @staticmethod54    def _build_percentage_column(orig_value: float, now_value: float) -> dict:55        """56        Build the percentage column based on the two given values57        :param orig_value: the original value58        :type orig_value: float59        :param now_value: the value of now60        :type now_value: float61        :return: a formatted dict containing the percentage increase between the two given values and ready to be added62        as a column inside a report line63        :rtype: dict64        """65        if not float_is_zero(orig_value, 6):66            res = round((now_value - orig_value) / orig_value * 100, 1)67            classes = ['number']68            if float_is_zero(res, precision_rounding=0.1):69                val = 0.070            elif (res > 0) == (orig_value > 0):71                classes.append('color-green')72                val = copysign(res, 1)73            else:74                classes.append('color-red')75                val = copysign(res, -1)76            return {77                'name': ('%s%%' % val),78                'no_format_name': val,79                'class': ' '.join(classes)80            }81        # res > 082        # orig > 0 :: GREEN83        # orig < 0 :: RED84        # res < 085        # orig < 0 :: GREEN86        # orig > 0 :: RED87        else:...mailroom.py
Source:mailroom.py  
...17          "Enter '3' - Quit"))18    print(prompt)19    response = input(">>>")20    return response21def append_amount(name):22    #add donation amount to the donation database if Donor name is on the list23    amount = float(input("Please enter a donation amount: "))24    for entry in donor_db:25        if name.title() == entry[0]:26            entry[1].append(float(amount))27            print("Thank you Dear,", name, "for your generous donation of", amount, "\n\nSincerely,\nThe Donor Gratitude Program \n")28            break29def add_name(name):30    #add Donor name to the list if missing31    new_name = (name.title(), [])32    donor_db.append(new_name)33    print(name.title(), "Added to the donors list")34def check_name(name):35    #check if donor name is on the list36    for entry in donor_db:37        if name == entry[0]:38            return True39def ty_note():40    """workflow that : 1) retrieves list of donors, 2) adds new donors to the database, 41       3) saves new donation amounts, and 4) prints thank you notes! """42    while True:43        name = input("\n Please enter a Donors name, or enter 'List' if you'd like to see the list of donors, or to exit say 'Main Menu' \n>>> ")44        if name == 'List':45            print("Here's the list of donors: \n")46            for i, v in enumerate(donor_db):47                print(v[0])48            continue49        elif name == "Main Menu":50            break51        else:52            if check_name(name) == True:53                append_amount(name)54            else:55                add_name(name)56                append_amount(name)57def gen_report():58    #Generate list of donors59    print("\n{:<20}|{:^15}|{:^15}|{:>15}".format("Donor Name", "Total Given", "Num Gifts", "Average Gift"))60    print("-"*68)61    for i in donor_db:62        total_given = sum(i[1])63        num_gifts = len(i[1])64        if total_given >0:65            avg_gift = total_given/num_gifts66        else:67            avg_gift = 068        print("{:<20} ${:>15,.2f} {:>15}  ${:>12,.2f}".format(i[0], total_given, num_gifts, avg_gift))69    print("\n")70def exit_prog():...AlipayAssetPointVoucherprodBenefittemplateAddResponse.py
Source:AlipayAssetPointVoucherprodBenefittemplateAddResponse.py  
...7        super(AlipayAssetPointVoucherprodBenefittemplateAddResponse, self).__init__()8        self._append_amount = None9        self._bill_no = None10    @property11    def append_amount(self):12        return self._append_amount13    @append_amount.setter14    def append_amount(self, value):15        self._append_amount = value16    @property17    def bill_no(self):18        return self._bill_no19    @bill_no.setter20    def bill_no(self, value):21        self._bill_no = value22    def parse_response_content(self, response_content):23        response = super(AlipayAssetPointVoucherprodBenefittemplateAddResponse, self).parse_response_content(response_content)24        if 'append_amount' in response:25            self.append_amount = response['append_amount']26        if 'bill_no' in response:...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
