Best Python code snippet using localstack_python
solution.py
Source:solution.py  
1import math2import heapq3example_input = """10 ORE => 10 A41 ORE => 1 B57 A, 1 B => 1 C67 A, 1 C => 1 D77 A, 1 D => 1 E87 A, 1 E => 1 FUEL"""9example_2 = """9 ORE => 2 A108 ORE => 3 B117 ORE => 5 C123 A, 4 B => 1 AB135 B, 7 C => 1 BC144 C, 1 A => 1 CA152 AB, 3 BC, 4 CA => 1 FUEL"""16answer_3 = 1331217example_3 = """157 ORE => 5 NZVS18165 ORE => 6 DCFZ1944 XJWVT, 5 KHKGT, 1 QDVJ, 29 NZVS, 9 GPVTF, 48 HKGWZ => 1 FUEL2012 HKGWZ, 1 GPVTF, 8 PSHF => 9 QDVJ21179 ORE => 7 PSHF22177 ORE => 5 HKGWZ237 DCFZ, 7 PSHF => 2 XJWVT24165 ORE => 2 GPVTF253 DCFZ, 7 NZVS, 5 HKGWZ, 10 PSHF => 8 KHKGT"""26example_4 = """2 VPVL, 7 FWMGM, 2 CXFTF, 11 MNCFX => 1 STKFG2717 NVRVD, 3 JNWZP => 8 VPVL2853 STKFG, 6 MNCFX, 46 VJHF, 81 HVMC, 68 CXFTF, 25 GNMV => 1 FUEL2922 VJHF, 37 MNCFX => 5 FWMGM30139 ORE => 4 NVRVD31144 ORE => 7 JNWZP325 MNCFX, 7 RFSQX, 2 FWMGM, 2 VPVL, 19 CXFTF => 3 HVMC335 VJHF, 7 MNCFX, 9 VPVL, 37 CXFTF => 6 GNMV34145 ORE => 6 MNCFX351 NVRVD => 8 CXFTF361 VJHF, 6 MNCFX => 4 RFSQX37176 ORE => 6 VJHF"""38answer_4 = 18069739answer_5 = 221073640example_5 = """171 ORE => 8 CNZTR417 ZLQW, 3 BMBT, 9 XCVML, 26 XMNCP, 1 WPTQ, 2 MZWV, 1 RJRHP => 4 PLWSL42114 ORE => 4 BHXH4314 VRPVC => 6 BMBT446 BHXH, 18 KTJDG, 12 WPTQ, 7 PLWSL, 31 FHTLT, 37 ZDVW => 1 FUEL456 WPTQ, 2 BMBT, 8 ZLQW, 18 KTJDG, 1 XMNCP, 6 MZWV, 1 RJRHP => 6 FHTLT4615 XDBXC, 2 LTCX, 1 VRPVC => 6 ZLQW4713 WPTQ, 10 LTCX, 3 RJRHP, 14 XMNCP, 2 MZWV, 1 ZLQW => 1 ZDVW485 BMBT => 4 WPTQ49189 ORE => 9 KTJDG501 MZWV, 17 XDBXC, 3 XCVML => 2 XMNCP5112 VRPVC, 27 CNZTR => 2 XDBXC5215 KTJDG, 12 BHXH => 5 XCVML533 BHXH, 2 VRPVC => 7 MZWV54121 ORE => 7 VRPVC557 XCVML => 6 RJRHP565 BHXH, 4 VRPVC => 5 LTCX"""57# 64238153290 too high58# 1850 is too low59# 466901 too low60# 475603 wrong61# 46953662real = """1 RNQHX, 1 LFKRJ, 1 JNGM => 8 DSRGV632 HCQGN, 1 XLNC, 4 WRPWG => 7 ZGVZL64172 ORE => 5 WRPWG657 MXMQ, 1 SLTF => 3 JTBLB661 DSRGV => 4 SLZF672 HDVD, 32 LFKRJ => 4 FCZQD689 LNRS, 18 WKMWF => 8 RNQRM6912 MWSGQ => 9 DCKC706 SLTF, 5 XLNC => 1 KFBX714 QNRZ, 1 QHLF, 15 FWSK => 9 SFJC729 KFBX, 15 RPKGX, 2 QNRZ => 6 LFKRJ738 SFJC, 6 ZQGL, 4 PFCGF => 3 THPCT742 RNQHX, 4 PFCGF, 1 ZQGL => 6 LNRS75195 ORE => 4 PTHDF763 FJKSL => 7 FWSK7712 KBJW, 9 MWSGQ => 9 WKMWF783 XLNC => 5 RPKGX79188 ORE => 7 FJKSL806 ZNPNM, 3 KHXPM, 3 TJXB => 2 HSDS811 DGKW, 17 XLNC => 1 PFCGF822 VRPJZ, 3 DSRGV => 5 MWSGQ8312 BJBQP, 5 XLNC => 4 HCQGN841 GFCGF => 3 HDVD8518 TJXB, 2 THPCT, 1 WPGQN => 4 KHXPM861 ZGVZL => 1 JNGM873 ZGVZL => 8 KBJW8812 GFCGF => 8 BJBQP897 MXMQ, 18 WRPWG => 9 XLNC9013 ZGVZL, 1 QNRZ => 6 RNQHX915 HRBG, 16 QNRZ => 9 WPGQN925 SFJC, 1 PFCGF, 1 KHXPM => 5 FXDMQ931 KBJW, 5 BNFV, 16 XLNC, 1 JNGM, 1 PFCGF, 1 ZNPNM, 4 FXDMQ => 5 VBWCM945 ZGVZL, 5 LFKRJ => 9 QHLF9514 JTBLB => 5 VRPJZ964 FWSK => 9 RXHC972 HRBG, 3 FCZQD => 8 DRLBG989 KLXC, 23 VBWCM, 44 VPTBL, 5 JRKB, 41 PFCGF, 4 WBCRL, 20 QNRZ, 28 SLZF => 1 FUEL991 DRLBG => 5 VPTBL10013 LNRS => 7 ZNPNM1013 WPGQN => 9 TJXB1025 GFCGF, 3 HCQGN => 5 ZQGL1031 KHXPM, 4 LMCSR, 1 QHLF, 4 WKMWF, 1 DGKW, 3 KBRM, 2 RNQRM => 4 KLXC104171 ORE => 8 ZJGSJ1053 ZJGSJ => 3 MXMQ106124 ORE => 5 SLTF10722 KHXPM, 10 FXDMQ => 6 KBRM1082 FCZQD => 8 LMCSR1097 DCKC, 8 HSDS, 7 PFCGF, 16 ZNPNM, 3 RNQRM, 3 WKMWF, 2 WBCRL, 14 RXHC => 7 JRKB1107 DCKC, 2 MWSGQ => 3 BNFV1112 ZQGL => 9 DGKW11222 WRPWG => 6 HRBG11322 KBJW, 1 KFBX, 1 THPCT => 6 WBCRL1144 WRPWG, 1 RXHC, 21 FWSK => 8 QNRZ1151 PTHDF => 8 GFCGF"""116def parse_input(input_map: str):117    mapping = {}118    for line in input_map.splitlines():119        inputs, output = line.split("=>")120        input_chems = []121        for x in inputs.split(","):122            input_chems.append(parse_chemical(x))123        output_chem = parse_chemical(output)124        mapping[output_chem] = input_chems125    return mapping126def get_required_ore(mapping):127    # contains list of reactions128    output_requirements = {}129    # contains the amount generated130    output_amounts = {}131    for amount, name in mapping.keys():132        output_amounts[name] = amount133        output_requirements[name] = mapping[(amount, name)]134    # the total amount that is required, no surplus135    required = {"FUEL": 1,}136    # the total amount that has already been created137    created = {}138    # the total surplus amount139    surplus = {}140    # priority = depth141    ingredient_set = set()142    ingredient_set.add("FUEL")143    ingredient_queue = [(1, "FUEL")]144    while len(ingredient_queue) > 0:145        print("\n------------------------------------------------------------------------")146        print(f"queue: {ingredient_queue}")147        depth, ingredient = heapq.heappop(ingredient_queue)148        print(f"ingredient {ingredient} depth: {depth}")149        if ingredient == "ORE":150            print(f"REQUIRED ORE: {required['ORE']}")151            continue152            # return required["ORE"]153        already_created = 0 if ingredient not in created else created[ingredient]154        total_required_amount = required[ingredient]155        current_surplus = 0 if ingredient not in surplus else surplus[ingredient]156        # how much created for each item157        each_created_amount = output_amounts[ingredient]158        if already_created >= total_required_amount:159            # already enough, don't need to dip into the cache160            print("---- ALREADY ENOUGH, NO CACHE NEEDED")161        elif total_required_amount <= (already_created + current_surplus):162            # if there's already enough within the surplus163            # no new ones need to be made164            surplus[ingredient] = (already_created + current_surplus) - total_required_amount165            assert surplus[ingredient] >= 0166            print("---- WITHIN SURPLUS")167            print(f"{ingredient} surplus {current_surplus} + {already_created} > {total_required_amount} new surplus {surplus[ingredient]}")168        else:169            required_amount = total_required_amount - (already_created + current_surplus)170            amount_to_create = math.ceil(required_amount / each_created_amount)171            created_amount = amount_to_create * each_created_amount172            print(f"ingredient {ingredient}")173            print(f"surplus {current_surplus} already {already_created} total required {total_required_amount}")174            print(f"required {total_required_amount} - {already_created} - {current_surplus} = {required_amount} ")175            new_surplus = (already_created + created_amount + current_surplus) - total_required_amount176            print(f"already created {already_created + created_amount + current_surplus} - required {total_required_amount} = surplus {new_surplus}")177            print(f"{ingredient} total = {already_created} + {created_amount} + {current_surplus} = {already_created + created_amount + current_surplus}")178            created[ingredient] = already_created + created_amount + current_surplus - new_surplus179            surplus[ingredient] = new_surplus180            assert created[ingredient] >= 0181            assert surplus[ingredient] >= 0182            assert created[ingredient] >= required[ingredient]183            print(f"created {created_amount} {ingredient} with a surplus of {new_surplus}")184            # get the required ingredients for this185            for required_amount, required_name in output_requirements[ingredient]:186                print(required)187                if required_name in required:188                    print(f"required for {required_name} is now {required[required_name]} + {required_amount} * {amount_to_create}")189                    required[required_name] += amount_to_create * required_amount190                else:191                    print(f"required for {required_name} is now {required_amount} * {amount_to_create}")192                    required[required_name] = amount_to_create * required_amount193                if required_name in ingredient_set:194                    # avoid duplicate195                    for i, x in enumerate(ingredient_queue):196                        if x[1] == required_name:197                            del ingredient_queue[i]198                    heapq.heappush(ingredient_queue, (depth + 1, required_name))199                else:200                    ingredient_set.add(required_name)201                    heapq.heappush(ingredient_queue, (depth + 1, required_name))202    return required["ORE"]203def get_part2(mapping, expected_min = 0):204    print("part2")205    for fuel in range(expected_min, 99999999999999999999, 1):206        result = get_required_ore_part2(mapping, fuel)207        print(f"{fuel} using {result} ore")208        if result is None or result > 1000000000000:209            # 12063757192210            # 1000000000000211            print(f"too much or none {fuel - 1}")212            return fuel - 1213def get_required_ore_part2(mapping, fuel):214    # contains list of reactions215    output_requirements = {}216    # contains the amount generated217    output_amounts = {}218    for amount, name in mapping.keys():219        output_amounts[name] = amount220        output_requirements[name] = mapping[(amount, name)]221    # the total amount that is required, no surplus222    required = {"FUEL": fuel,}223    # the total amount that has already been created224    created = {}225    # the total surplus amount226    surplus = {}227    # priority = depth228    ingredient_set = set()229    ingredient_set.add("FUEL")230    ingredient_queue = [(1, "FUEL")]231    while len(ingredient_queue) > 0:232        # print("\n------------------------------------------------------------------------")233        # print(f"queue: {ingredient_queue}")234        depth, ingredient = heapq.heappop(ingredient_queue)235        # print(f"ingredient {ingredient} depth: {depth}")236        if ingredient == "ORE":237            # print(f"REQUIRED ORE: {required['ORE']}")238            continue239            # return required["ORE"]240        already_created = 0 if ingredient not in created else created[ingredient]241        total_required_amount = required[ingredient]242        current_surplus = 0 if ingredient not in surplus else surplus[ingredient]243        # how much created for each item244        each_created_amount = output_amounts[ingredient]245        if already_created >= total_required_amount:246            # already enough, don't need to dip into the cache247            # print("---- ALREADY ENOUGH, NO CACHE NEEDED")248            pass249        elif total_required_amount <= (already_created + current_surplus):250            # if there's already enough within the surplus251            # no new ones need to be made252            surplus[ingredient] = (already_created + current_surplus) - total_required_amount253            assert surplus[ingredient] >= 0254            # print("---- WITHIN SURPLUS")255            # print(f"{ingredient} surplus {current_surplus} + {already_created} > {total_required_amount} new surplus {surplus[ingredient]}")256        else:257            required_amount = total_required_amount - (already_created + current_surplus)258            amount_to_create = math.ceil(required_amount / each_created_amount)259            created_amount = amount_to_create * each_created_amount260            # print(f"ingredient {ingredient}")261            # print(f"surplus {current_surplus} already {already_created} total required {total_required_amount}")262            # print(f"required {total_required_amount} - {already_created} - {current_surplus} = {required_amount} ")263            new_surplus = (already_created + created_amount + current_surplus) - total_required_amount264            # print(f"already created {already_created + created_amount + current_surplus} - required {total_required_amount} = surplus {new_surplus}")265            # print(f"{ingredient} total = {already_created} + {created_amount} + {current_surplus} = {already_created + created_amount + current_surplus}")266            created[ingredient] = already_created + created_amount + current_surplus - new_surplus267            surplus[ingredient] = new_surplus268            assert created[ingredient] >= 0269            assert surplus[ingredient] >= 0270            assert created[ingredient] >= required[ingredient]271            # print(f"created {created_amount} {ingredient} with a surplus of {new_surplus}")272            # get the required ingredients for this273            for required_amount, required_name in output_requirements[ingredient]:274                # print(required)275                if required_name in required:276                    # print(f"required for {required_name} is now {required[required_name]} + {required_amount} * {amount_to_create}")277                    required[required_name] += amount_to_create * required_amount278                else:279                    # print(f"required for {required_name} is now {required_amount} * {amount_to_create}")280                    required[required_name] = amount_to_create * required_amount281                if required_name in ingredient_set:282                    # avoid duplicate283                    for i, x in enumerate(ingredient_queue):284                        if x[1] == required_name:285                            del ingredient_queue[i]286                    heapq.heappush(ingredient_queue, (depth + 1, required_name))287                else:288                    ingredient_set.add(required_name)289                    heapq.heappush(ingredient_queue, (depth + 1, required_name))290    # return required["ORE"]291    if "ORE" in required:292        return required["ORE"]293    return None294def calc_required(mapping):295    required = {"FUEL": 1,}296    surplus = {}297    # active_set = set()298    active_set = []299    active_set.append("FUEL")300    # key_name = "FUEL"301    while len(active_set) > 0:302        print(required)303        # key_name = list(active_set)[0]304        key_name = active_set.pop()305        # get the key for the key name306        # key = list(filter(lambda x: x[1] == key_name, list(mapping.keys())))307        key = [x for x in mapping.keys() if x[1] == key_name]308        print(active_set)309        print(key_name)310        print(key)311        key = key[0]312        existing_surplus = 0 if key_name not in surplus else surplus[key_name]313        required_amount = required[key_name] - existing_surplus314        produced = key[0]315        multiplier = math.ceil(required_amount / produced)316        created_surplus = multiplier * (required_amount % produced)317        surplus[key_name] = created_surplus318        print(f"{key_name} produces {produced} requires {required_amount} surplus {created_surplus} mul {multiplier}")319        # remove this key from the dict320        # del active_set[key_name]321        if key_name in active_set:322            active_set.remove(key_name)323        inputs = mapping[key]324        for input_amount, input_name in inputs:325            if input_name in required:326                current = required[input_name]327                print(f"current {input_name} already has {current}, adding {input_amount * multiplier}")328                required[input_name] = input_amount * multiplier329            else:330                required[input_name] = input_amount * multiplier331            if input_name != "ORE":332                # active_set.add(input_name)333                if input_name in active_set:334                    print(f"{input_name} in {active_set}")335                    active_set.remove(input_name)336                active_set.append(input_name)337        338        # ensure that the required doesn't only contain ORE339        # if "ORE" in required:340        #     print(f"ore {ore} + {required['ORE']}")341        #     ore += required["ORE"]342        #     del required["ORE"]343    return required["ORE"]344def parse_chemical(input_chem: str):345    chem = input_chem.strip().split(" ")346    return int(chem[0]), chem[1]347if __name__ == "__main__":348    print(example_input)349    mapping = parse_input(example_input)350    print(mapping)351    result = get_required_ore(mapping)352    print(result)353    assert result == 31354    mapping = parse_input(example_2)355    assert get_required_ore(mapping) == 165356    mapping = parse_input(example_3)357    assert get_required_ore(mapping) == answer_3358    assert get_part2(mapping, 82892700) == 82892753359    mapping = parse_input(example_4)360    assert get_required_ore(mapping) == answer_4361    assert get_part2(mapping, 5586000) == 5586022362    mapping = parse_input(example_5)363    assert get_required_ore(mapping) == answer_5364    assert get_part2(mapping, 460600) == 460664365    mapping = parse_input(real)366    result = get_required_ore(mapping)367    print(f"real result: {result}")368    assert result == 469536369    # part 2370    result = get_part2(mapping, 3299999)371    # 3343477...convert_video_to_images.py
Source:convert_video_to_images.py  
1# Program to convert videos into frames for dataset preparation2# This is done to manually delete unnecessary / mislabelled frames3import cv2, sys, os4from tqdm import tqdm5def main():6    # Take video location and frame name off commandline7    vid_location = sys.argv[1] # Folder containing videos8    # Take name of folders off cmd line 9    name_1 = sys.argv[2]10    name_2 = sys.argv[3]11    os.chdir(vid_location) # Set working dir to vid location12    required_name = "fitness_poses_images_in"13    if not os.path.exists(os.path.join(os.getcwd(), required_name)):14        # Make the dir if it does not exist15        os.mkdir(os.path.join(os.getcwd(), required_name))16    if not os.path.exists(os.path.join(os.getcwd(), required_name, name_1)):17        # Make the dir if it does not exist18        os.mkdir(os.path.join(os.getcwd(), required_name, name_1))19    if not os.path.exists(os.path.join(os.getcwd(), required_name, name_2)):20        # Make the dir if it does not exist21        os.mkdir(os.path.join(os.getcwd(), required_name, name_2))22    count = 023    for video in tqdm(os.listdir()):24        # Determine whether correct or incorrect label25        is_correct = True26        if video.split("_")[1].strip() == "incorrect":27            is_correct = False28        if (video.split(".")[-1]).strip() == "mp4": # only want videos29            # Read video30            videoCapture = cv2.VideoCapture(os.path.join(os.getcwd(), video))31            success, image = videoCapture.read()32            if is_correct:33                os.chdir(os.path.join(os.getcwd(), required_name, name_1))34                name = name_135            else:36                os.chdir(os.path.join(os.getcwd(), required_name, name_2))37                name = name_238            while success:39                cv2.imwrite("{:}_{:}.jpg".format(name, count), image)     # save frame as JPEG file      40                success, image = videoCapture.read()41                #print('Saved a new frame: ', success)42                count += 143        os.chdir(vid_location) # Set working dir to vid location44if __name__ == '__main__':...model.py
Source:model.py  
1from prolog.query import QueryVar, QuerySet2from prolog.predicate import predicate3from prolog.orm.exceptions import ORMException4from prolog.orm.utils import process_var5from typing import Union6Arg = Union[str, int, list, QueryVar]7class Predicate:8    @classmethod9    def filter(cls, *args: Arg, **kwargs) -> QuerySet:10        # TODO: type checks11        query_args = []12        pre_set = dict()13        format_args = ", ".join("{}" for _ in cls.__annotations__)14        format_predicate = predicate(f"{cls.__name__.lower()}({format_args})")15        for i, required_name in enumerate(cls.__annotations__):16            query_arg = QueryVar(required_name.capitalize())17            if required_name in kwargs:18                query_arg = kwargs[required_name]19                pre_set[required_name] = query_arg20            elif len(args) > i:21                query_arg = args[i]22                pre_set[required_name] = query_arg23            query_args.append(query_arg)24        for k, v in pre_set.items():25            pre_set[k] = process_var(v)26        return QuerySet(format_predicate(*query_args), pre_set=pre_set, dataclass=cls)27    def __str__(self):28        args = ", ".join("{}" for _ in self.__annotations__)29        query_set = predicate(f"{self.__class__.__name__.lower()}({args}).")...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!!
