Best Python code snippet using hypothesis
create_constraint_file.py
Source:create_constraint_file.py  
...106                diff_lower = lower - upper107                diff_upper = c1_upper - c2_lower108                diff_constraints_bounds["{} - {}".format(cls1, cls2)] = (diff_lower, diff_upper)109    return diff_constraints_bounds110def get_all_bounds(constraints_path):111    constraints_parser = ConstraintsParser(constraints_path)112    constraints_bounds = build_diff_constraints_from_lower_and_upper(constraints_parser)113    for cls, lower in constraints_parser.lower_bounds.items():114        constraints_bounds[cls] = (lower, None)115    for cls, upper in constraints_parser.upper_bounds.items():116        if cls in constraints_bounds:117            lower = constraints_bounds[cls][0]118            constraints_bounds[cls] = (lower, upper)119        else:120            constraints_bounds[cls] = (None, upper)121    return constraints_bounds122def write_bounds_into_file(all_bounds_dict, dest_full_path):123    first_line=True124    with open(dest_full_path, "w") as f:125        for name, bounds in all_bounds_dict.items():126            if first_line:127                first_line = False128            else:129                f.write("\n")130            if bounds[0] is not None and bounds[1] is not None:131                f.write("{} < {} < {}".format(format(bounds[0], '.2f'), name, format(bounds[1], '.2f')))132            elif bounds[0] is not None:133                f.write("{} > {}".format(name, format(bounds[0], '.2f')))134            else:135                f.write("{} < {}".format(name, format(bounds[1], '.2f')))136def get_args_parser():137    parser = argparse.ArgumentParser(description='Process constraint collector args.')138    parser.add_argument('--src_path', '-s', type=str, required=True)139    parser.add_argument('--dest_path',  '-d', type=str, required=True)140    parser.add_argument('--expand_constraints',  '-expand', action="store_true")141    parser.add_argument('--create_auto_constraints', '-auto', action="store_true")142    parser.add_argument('--parse_crowd', '-crowd', action="store_true")143    parser.add_argument('--data_path',  '-data', type=str, required='-crowd' in sys.argv)144    parser.add_argument('--auto_eps', '-e', type=float, default=0.1)145    parser.add_argument('--neg_label', type=str, default="0")146    parser.add_argument('--pos_label', type=str, default="1")147    return parser148def main():149    args = get_args_parser().parse_args()150    print(vars(args))151    if args.expand_constraints:152        if not os.path.exists(args.dest_path):153            os.makedirs(args.dest_path)154        dest_file = os.path.join(args.dest_path, "{}_full.txt".format(os.path.abspath(args.src_path).split(".")[0]))155        all_bounds = get_all_bounds(args.src_path)156        write_bounds_into_file(all_bounds, dest_file)157    elif args.create_auto_constraints:158        print(os.path.dirname(args.dest_path))159        if not os.path.exists(os.path.dirname(args.dest_path)):160            print("create directory " + os.path.dirname(args.dest_path))161            os.makedirs(os.path.dirname(args.dest_path))162        # creates constraints from split dir163        labels_map = {args.pos_label: 1, args.neg_label: 0}164        true_indoor_percent = get_indoor_size(args.src_path, labels_map)165        bounds = create_lower_and_upper_bounds(true_indoor_percent, args.auto_eps)166        diff_bounds = create_mutual_bounds(true_indoor_percent, args.auto_eps)167        all_bounds = {**bounds, **diff_bounds}168        write_bounds(all_bounds, args.dest_path)169    elif args.parse_crowd:170        if not os.path.exists(args.dest_path):171            os.makedirs(args.dest_path)172        true_positive_percent_for_action = parse_crowd_data(args.src_path, args.data_path)173        for action in true_positive_percent_for_action:174            bounds = create_lower_and_upper_bounds(true_positive_percent_for_action[action], args.auto_eps)175            diff_bounds = create_mutual_bounds(true_positive_percent_for_action[action], args.auto_eps)176            all_bounds = {**bounds, **diff_bounds}177            dest_path = os.path.join(args.dest_path, "{}_constraints.txt".format(action))178            write_bounds(all_bounds, dest_path)179if __name__ == "__main__":180    main()181# PATH = "C:\\Users\\lotan\\Documents\\studies\\phoenix\\projects\\ballpark_indoor_outdoor\\explore_constraints\\teaching_constraints.txt"182# DEST = "C:\\Users\\lotan\\Documents\\studies\\phoenix\\projects\\ballpark_indoor_outdoor\\explore_constraints\\teaching_constraints_full.txt"183# all_bounds = get_all_bounds(PATH)...guided_crop.py
Source:guided_crop.py  
1import os2from pyrecon.utils.explore_files import findFiles3from pyrecon.utils.get_input import floatInput4from PIL import Image as PILImage5PILImage.MAX_IMAGE_PIXELS = None6def findBounds(series, obj_name):7    """Finds the bounds of a specified object on a single section file.8    """9    all_bounds = {}10    for section_num in series.sections:11        section = series.sections[section_num]12        # obtain list of all contours with obj_name13        all_contours = []14        for contour in section.contours:15            if contour.name == obj_name:16                all_contours.append(contour)17        # return None if contour not found in section18        if len(all_contours) == 0:19            all_bounds[section.name] = None20        else:21            # compile all transformed points22            all_points = []23            for contour in all_contours:24                fixed_points = contour.transform.transformPoints(contour.points)25                for point in fixed_points:26                    all_points.append(point)27            # get the domain transformation and inverse transformation28            domain_tform = section.images[0].transform # ASSUMES A SINGLE DOMAIN IMAGE29            domain_itform = domain_tform.inverse30            # compile points transformed by domain inverse transformation (ditform)31            all_points_ditform = domain_itform.transformPoints(all_points)32            x_vals = []33            y_vals = []34            for point in all_points_ditform:35                x_vals.append(point[0])36                y_vals.append(point[1])37            # get min and max values from points transformed by ditform38            x_min_ditform = min(x_vals)39            y_min_ditform = min(y_vals)40            x_max_ditform = max(x_vals)41            y_max_ditform = max(y_vals)42            # undo ditform43            bounds = domain_tform.transformPoints([(x_min_ditform, y_min_ditform), (x_max_ditform, y_max_ditform)])44            xmin = bounds[0][0]45            xmax = bounds[1][0]46            ymin = bounds[0][1]47            ymax = bounds[1][1]48            # return bounds fixed to Reconstruct space49            all_bounds[section.name] = (xmin, xmax, ymin, ymax)50    # fill in bounds data on sections where the object doesn't exist51    # if the first section(s) do not have the object, then fill it in with first object instance52    prev_bounds = None53    obj_found = False54    for bounds in all_bounds:55        if all_bounds[bounds] != None:56            prev_bounds = all_bounds[bounds]57            obj_found = True58            break59    # return None if obj was not found in entire series60    if not obj_found:61        return None62    # set any bounds points that are None to the previous bounds63    for bounds in all_bounds:64        if all_bounds[bounds] == None:65            all_bounds[bounds] = prev_bounds66        prev_bounds = all_bounds[bounds]67    # return bounds dictionary68    return all_bounds69def guidedCrop(series, obj_name, tform_data, images_dict, rad, progbar=None):70    """ Create a crop around an object.71    ENSURE THAT CROP FOCUS IS ALREADY SET TO GLOBAL BEFORE CALLING THIS FUNCTION.72    """73    # find the bounds for the object on each section74    bounds_dict = findBounds(series, obj_name)75    # check if trace was found in the series76    if not bounds_dict:77        raise Exception("This trace does not exist in this series.")78    79    # create the folder for the cropped images80    if not os.path.isdir("Cropped Images"):81        os.mkdir("Cropped Images")82    new_dir = "Cropped Images/" + obj_name83    os.mkdir(new_dir)84    # set up the tform_data file85    tform_data["LOCAL_" + obj_name] = {}86    # iterat through all section files87    if progbar:88        final_value = len(series.sections)89        prog_value = 090    for section_num in series.sections:91        if progbar:92            progbar.update_bar(prog_value/final_value * 100)93            prog_value += 194        section = series.sections[section_num]95        # set up the tform_data file96        tform_data["LOCAL_" + obj_name][section.name] = {}97        # fix the coordinates to the picture98        global_tform = section.images[0].transform99        xmin, xmax, ymin, ymax = bounds_dict[section.name]100        min_max_coords = global_tform.inverse.transformPoints([(xmin, ymin), (xmax, ymax)])101        # translate coordinates to pixels102        pix_per_mic = 1.0 / section.images[0].mag # get image magnification103        xshift_pix = int((min_max_coords[0][0] - rad) * pix_per_mic)104        if xshift_pix < 0:105            xshift_pix = 0106        yshift_pix = int((min_max_coords[0][1] - rad) * pix_per_mic)107        if yshift_pix < 0:108            yshift_pix = 0109        # write the shifted origin to the tform_data file110        tform_data["LOCAL_" + obj_name][section.name]["xshift_pix"] = xshift_pix111        tform_data["LOCAL_" + obj_name][section.name]["yshift_pix"] = yshift_pix112        # write identity transformation as Delta transformation113        tform_data["LOCAL_" + obj_name][section.name]["xcoef"] = [0,1,0,0,0,0]114        tform_data["LOCAL_" + obj_name][section.name]["ycoef"] = [0,0,1,0,0,0]115        # get the name/path of the desired image file from dictionary116        file_path = images_dict[section.name]117        file_name = file_path[file_path.rfind("/")+1:]118        print("\nWorking on " + file_name + "...")119        120        # open original image121        img = PILImage.open(file_path)122        # get image dimensions123        img_length, img_height = img.size124        # get the pixel coordinates for each corner of the crop125        left = int((min_max_coords[0][0] - rad) * pix_per_mic)126        bottom = img_height - int((min_max_coords[0][1] - rad) * pix_per_mic)127        right = int((min_max_coords[1][0] + rad) * pix_per_mic)128        top = img_height - int((min_max_coords[1][1] + rad) * pix_per_mic)129        130        # if crop exceeds image boundary, cut it off131        if left < 0: left = 0132        if right >= img_length: right = img_length-1133        if top < 0: top = 0134        if bottom >= img_height: bottom = img_height-1135        # crop the photo136        cropped_src = new_dir + "/" + file_name137        cropped = img.crop((left, top, right, bottom))138        cropped.save(cropped_src)139        # store the local src for the image in tform_data...16.py
Source:16.py  
1from utils.utils_15 import get_raw_items, get_regex_search, get_regex_findall, regex, translate2from utils.utils_15 import GameConsole, TweakedGameConsole, memo3from inputs.input_16 import main_input4from itertools import combinations5import copy6import re7from collections import Counter8def get_parsed(raw_input):9    sections = get_raw_items(raw_input, split_token='\n\n')10    # section 011    rules = {}12    for line in sections[0].split('\n'):13        search_results = get_regex_search(line, r'(.*): (\d+)\-(\d+) or (\d+)\-(\d+)')14        field = search_results[0]15        lb1, ub1, lb2, ub2 = (int(x) for x in search_results[1:])16        rules[field] = ((lb1, ub1), (lb2, ub2))17    # section 118    section_1 = get_raw_items(sections[1], split_token='\n')[1]19    my_ticket = [int(x) for x in section_1.split(',')]20    # section 221    section_2 = get_raw_items(sections[2], split_token='\n')[1:]22    other_tickets = [[int(x) for x in line.split(',')] for line in section_2]23    return rules, my_ticket, other_tickets24sample_input_0 = """class: 1-3 or 5-725row: 6-11 or 33-4426seat: 13-40 or 45-5027your ticket:287,1,1429nearby tickets:307,3,473140,4,503255,2,203338,6,12"""34sample_input_1 = """class: 0-1 or 4-1935row: 0-5 or 8-1936seat: 0-13 or 16-1937your ticket:3811,12,1339nearby tickets:403,9,184115,1,5425,14,9"""43def part_1(raw_input):44    rules, my_ticket, other_tickets = get_parsed(raw_input)45    all_bounds = []46    for (lb1, ub1), (lb2, ub2) in rules.values():47        all_bounds.append((lb1, ub1))48        all_bounds.append((lb2, ub2))49    answer = 050    for t in other_tickets:51        for x in t:52            if not any(lb <= x <= ub for (lb, ub) in all_bounds):53                answer += x54    print(f'Part1: {answer}')55def is_valid(ticket, all_bounds):56    for x in ticket:57        if not any(lb <= x <= ub for (lb, ub) in all_bounds):58            return False59    return True60def part_2(raw_input):61    rules, my_ticket, other_tickets = get_parsed(raw_input)62    all_bounds = []63    for (lb1, ub1), (lb2, ub2) in rules.values():64        all_bounds.append((lb1, ub1))65        all_bounds.append((lb2, ub2))66    valid_tickets = [my_ticket] + [t for t in other_tickets if is_valid(t, all_bounds)]67    all_possible_fields = []68    for i, fvs in enumerate(zip(*valid_tickets)):69        possible_fields = []70        for field, ((lb1, ub1), (lb2, ub2)) in rules.items():71            if all(((lb1 <= fv <= ub1) or (lb2 <= fv <= ub2)) for fv in fvs):72                possible_fields.append(field)73        all_possible_fields.append(possible_fields)74    finalized_assignments = {}75    while len(finalized_assignments) < len(rules):76        for i, possible_fields in enumerate(all_possible_fields):77            if len(possible_fields) == 1:78                field = possible_fields[0]79                finalized_assignments[field] = i80                for possible_fields in all_possible_fields:81                    try:82                        possible_fields.remove(field)83                    except ValueError:84                        pass85                continue86    print(finalized_assignments)87    answer = 188    for field, index in finalized_assignments.items():89        if field.startswith('departure'):90            answer *= my_ticket[index]91    print(f'Part2: {answer}')92# part_1(sample_input_0)93# part_1(main_input)94part_2(sample_input_1)...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!!
