Best Python code snippet using hypothesis
extra_tags.py
Source:extra_tags.py
1from django import template2from django.utils.html import format_html3register = template.Library()4@register.simple_tag5def image(file, max_size=300):6 from main import settings7 if file:8 title = '<img src="/' + settings.MEDIA_URL + str(file) + '" style="max-width: '+str(max_size)+'px; max-width: '+str(max_size)+'px;"/>'9 return image_link(file, title)10 else:11 return ''12@register.simple_tag13def image_link(file, title='ÐÑоÑмоÑÑ', classes=''):14 from main import settings15 from PIL import Image16 import os17 if file:18 width = 100019 height = 80020 try:21 f = Image.open(os.path.join(settings.MEDIA_ROOT,str(file)))22 width, height = f.size23 ratio = width / height24 if width > 1000:25 width = 100026 height = width / ratio27 elif height > 800:28 height = 80029 width = height * ratio30 except IOError:31 pass32 html = '<a href="#" class="'+classes+'" onclick=\''33 html += ' window.open("/' + settings.MEDIA_URL + str(file) + '", "_blank", "toolbar=no,scrollbars=yes,resizable=yes,top=50,left=100,width='+str(width)+',height='+str(height)+'"); '34 html += ' return false; '35 html += '\'>'+title+'</a>'36 return format_html(html)37 else:38 return ''39@register.simple_tag40def get_label(instance, field_name):41 if instance:42 #try:43 return instance._meta.get_field(field_name).verbose_name44 #except:45 # return None46 else:47 return None48@register.simple_tag49def month(month):50 if month != '':51 from main.structures import MONTHS52 return MONTHS[int(month)-1][1]53 else:54 return ''55@register.filter56def num(value, precision=2):57 if value:58 return ("{:,."+str(precision)+"f}").format(value).replace(',', ' ').replace('.',',')59 else:60 return ''61@register.filter62def rub(value):63 if value:64 return "{:,.2f}".format(value).replace(',', ' ').replace('.',',')+' ÑÑб.'65 else:66 return ''67@register.filter68def boolean(value):69 if value:70 return 'Ðа'71 else:72 return 'ÐеÑ'73@register.filter74def empty(value):75 if value is not None:76 return value77 else:78 return ''79@register.inclusion_tag('main/paginator.html', takes_context=True)80def paginator(context, paginated_list):81 if 'is_mobile' in context:82 return {'list': paginated_list, 'is_mobile': context['is_mobile']}83 else:84 return {'list': paginated_list}85@register.inclusion_tag('form.html', takes_context=True)86def table_form(context, form_var, rows_only=False):87 if 'is_mobile' in context:88 return {'form': form_var, 'rows_only': rows_only, 'is_mobile': context['is_mobile']}89 else:90 return {'form': form_var, 'rows_only': rows_only}91@register.filter92def expire(value, days):93 from datetime import date, timedelta94 if isinstance(value, date):95 if value < date.today():96 return format_html('<span class="date-expired">'+value.strftime('%d.%m.%Y')+'</span>')97 elif value - timedelta(days=days) < date.today():98 return format_html('<span class="date-expiring">'+value.strftime('%d.%m.%Y')+'</span>')99 else:100 return value.strftime('%d.%m.%Y')101@register.filter102def spaces(value):103 value_str = str(value)104 strlen = len(value_str)105 if strlen > 0:106 comma_position = value_str.find(',')107 if comma_position > 3:108 for i in range(3, comma_position, 3):109 value_str = value_str[0:comma_position-i]+' '+value_str[comma_position-i:]110 elif comma_position < 0:111 if strlen > 3:112 for i in range(3, strlen, 3):113 value_str = value_str[0:strlen - i] + ' ' + value_str[strlen - i:]114 return value_str115 else:116 return ''117@register.filter118def sum_vals(array, field_name):119 return sum([getattr(elem, field_name) for elem in array])120@register.filter121def count_vals(array, field_name):122 return sum([1 for elem in array if getattr(elem, field_name)])123@register.filter124def cut_length(value, length=50):125 if len(value) > length:126 return value[:length]+'...'127 else:...
day04b.py
Source:day04b.py
1#!/usr/bin/env python32class Board(object):3 def __init__(self, squares):4 self.squares = squares5 self.positions = {}6 self.covered_positions = set()7 self.already_won = False8 self.num_rows = len(squares)9 if len(set(map(len, squares))) > 1:10 raise ValueError("Can't handle jagged board")11 self.num_cols = len(squares[0])12 for y in range(self.num_rows):13 for x in range (self.num_cols):14 self.positions[self.squares[y][x]] = (x, y)15 def check_bingo(self, number):16 if (not self.already_won) and (number in self.positions):17 self.covered_positions.add(self.positions[number])18 cols_only = [ x for (x,y) in self.covered_positions ]19 if self.num_cols in [ cols_only.count(i) for i in set(cols_only) ]:20 self.already_won = True21 return True22 rows_only = [ y for (x,y) in self.covered_positions ]23 if self.num_rows in [ rows_only.count(i) for i in set(rows_only) ]:24 self.already_won = True25 return True26 return False27 def get_unmarked_sum(self):28 squares = self.squares29 for col, row in self.covered_positions:30 squares[row][col] = 031 return sum([sum(row) for row in squares])32 def __repr__(self):33 return '\n'.join([' '.join(map(str,row)) for row in self.squares])34def get_board(infile):35 squares = []36 nextline = infile.readline().strip()37 if not len(nextline):38 return None39 while len(nextline):40 squares.append([*map(int, nextline.split())])41 nextline = infile.readline().strip()42 return Board(squares)43def get_drawing(infile):44 numbers = map(int, infile.readline().strip().split(','))45 infile.readline()46 return numbers47if __name__ == "__main__":48 boards = []49 with open("day04.txt", "r") as inputfile:50 numbers = get_drawing(inputfile)51 board = get_board(inputfile)52 while board:53 boards.append(board)54 board = get_board(inputfile)55 last_winner = False56 for number in numbers:57 bingo_results = [ board.check_bingo(number) for board in boards ]58 if any(bingo_results):59 last_winner = (bingo_results.index(True), number)60 if (last_winner):61 winner, number = last_winner62 print("Board {} won last, when {} was called!".format(winner, number))63 print(boards[winner])64 print("Sum of unmarked squares: {}".format(boards[winner].get_unmarked_sum()))65 print("Puzzle answer (sum * number): {}".format(boards[winner].get_unmarked_sum() * number))66 else:...
day04a.py
Source:day04a.py
1#!/usr/bin/env python32class Board(object):3 def __init__(self, squares):4 self.squares = squares5 self.positions = {}6 self.covered_positions = set()7 self.num_rows = len(squares)8 if len(set(map(len, squares))) > 1:9 raise ValueError("Can't handle jagged board")10 self.num_cols = len(squares[0])11 for y in range(self.num_rows):12 for x in range (self.num_cols):13 self.positions[self.squares[y][x]] = (x, y)14 def check_bingo(self, number):15 if number in self.positions:16 self.covered_positions.add(self.positions[number])17 cols_only = [ x for (x,y) in self.covered_positions ]18 if self.num_cols in [ cols_only.count(i) for i in set(cols_only) ]:19 return True20 rows_only = [ y for (x,y) in self.covered_positions ]21 if self.num_rows in [ rows_only.count(i) for i in set(rows_only) ]:22 return True23 return False24 def get_unmarked_sum(self):25 squares = self.squares26 for col, row in self.covered_positions:27 squares[row][col] = 028 return sum([sum(row) for row in squares])29 def __repr__(self):30 return '\n'.join([' '.join(map(str,row)) for row in self.squares])31def get_board(infile):32 squares = []33 nextline = infile.readline().strip()34 if not len(nextline):35 return None36 while len(nextline):37 squares.append([*map(int, nextline.split())])38 nextline = infile.readline().strip()39 return Board(squares)40def get_drawing(infile):41 numbers = map(int, infile.readline().strip().split(','))42 infile.readline()43 return numbers44if __name__ == "__main__":45 boards = []46 with open("day04.txt", "r") as inputfile:47 numbers = get_drawing(inputfile)48 board = get_board(inputfile)49 while board:50 boards.append(board)51 board = get_board(inputfile)52 found_winner = False53 for number in numbers:54 bingo_results = [ board.check_bingo(number) for board in boards ]55 if any(bingo_results):56 found_winner = True57 break58 else:59 print("No bingos! (This should probably not happen)")60 if (found_winner):61 winner = bingo_results.index(True)62 print("Board {} won when {} was called!".format(winner, number))63 print(boards[winner])64 print("Sum of unmarked squares: {}".format(boards[winner].get_unmarked_sum()))...
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!!