Best Python code snippet using playwright-python
parser.py
Source:parser.py
...253 raise FlexParserError(254 f"Can't convert {value!r} to {Type}"255 )256 return convert257def make_optional(func):258 def optional_convert(value):259 return None if value in ("", "-", "--", "N/A") else func(value)260 return optional_convert261convert_string = make_optional(make_converter(str, prep=utils.identity_func))262convert_int = make_converter(int, prep=utils.identity_func)263# IB sends "Y"/"N" for True/False264convert_bool = make_converter(bool, prep=lambda x: {"Y": True, "N": False}[x])265# IB sends numeric data with place delimiters (commas)266convert_decimal = make_converter(267 decimal.Decimal,268 prep=lambda x: x.replace(",", "")269)270convert_date = make_converter(datetime.date, prep=prep_date)271convert_time = make_converter(datetime.time, prep=prep_time)272convert_datetime = make_converter(datetime.datetime, prep=prep_datetime)273convert_sequence = make_converter(tuple, prep=prep_sequence)274convert_code_sequence = make_converter(tuple, prep=prep_code_sequence)275def convert_enum(Type, value):276 # Work around old versions of values; convert to the new format277 if Type is enums.CashAction and value == "Deposits/Withdrawals":278 value = "Deposits & Withdrawals"279 # Work around for Orders with orderType like "LMT;MKT" -> "MULTIPLE"280 if Type is enums.OrderType and ';' in value:281 value = "MULTIPLE"282 elif Type is enums.TransferType and value == "ACAT":283 value = "ACATS"284 # Enums bind custom names to the IB-supplied values.285 # To convert, just do a by-value lookup on the incoming string.286 # https://docs.python.org/3/library/enum.html#programmatic-access-to-enumeration-members-and-their-attributes287 return Type(value) if value != "" else None288ATTRIB_CONVERTERS = {289 "str": convert_string,290 "Optional[str]": convert_string,291 "int": convert_int,292 "Optional[int]": make_optional(convert_int),293 "bool": convert_bool,294 "Optional[bool]": make_optional(convert_bool),295 "decimal.Decimal": convert_decimal,296 "Optional[decimal.Decimal]": make_optional(convert_decimal),297 "datetime.date": convert_date,298 "Optional[datetime.date]": make_optional(convert_date),299 "datetime.time": convert_time,300 "Optional[datetime.time]": make_optional(convert_time),301 "datetime.datetime": convert_datetime,302 "Optional[datetime.datetime]": make_optional(convert_datetime),303 "Tuple[str, ...]": convert_sequence,304 "Tuple[enums.Code, ...]": convert_code_sequence,305}306"""Map of FlexElement attribute type hint to corresponding converter function.307"""308ATTRIB_CONVERTERS.update(309 {310 f"Optional[enums.{Enum.__name__}]": functools.partial(convert_enum, Type=Enum)311 for Enum in enums.ENUMS312 }313)314"""Map all Enum subclasses as Optional.315"""316###############################################################################...
app.py
Source:app.py
...62 nbPlaylist = IntegerField('Input the maximum number of playlists you want to STT API with',[validators.optional()])63 nbSamples = IntegerField('Input the maximum number of musics per playlists you want to STT API with',[validators.optional()])646566def make_optional(field):67 field.validators.insert(0, Optional())6869def handleNoneField(field):70 if field == None or field == '':71 return ''72 else : return field7374if emptyDB == 'empty': 75 @app.route('/', methods=['GET', 'POST'])76 def login():77 '''78 is called if fieldProcessing find out 'Spotify ID' case in sqlite is empty 79 '''8081 form = RegisterForm()82 # make_optional(form)83 if request.method == 'POST' : #if form.validate_on_submit():84 new_user = User(spotifyId=form.spotifyId.data, spotifyPlaylist=form.spotifyPlaylist.data, spotifySecret=form.spotifySecret.data, sttapiCheckbox=form.sttapiCheckbox.data, stthintCheckbox=form.stthintCheckbox.data, artistAlbumTracks=form.artistAlbumTracks.data, nbPlaylist=form.nbPlaylist.data, nbSamples=form.nbSamples.data)85 db.session.add(new_user) 86 db.session.commit()87 return '<h1>You are awesome ! You successfully configured Speech API Tester parameters ;) Now go back to your consol and hit Ctrl+C </h1>'88 return render_template('login.html', form=form)89 # return '<h1> The parameters you intered are not valide please try again </h1>' 909192 # new_user = User(spotifyId=make_optional(form.spotifyId.data), spotifyPlaylist=make_optional(form.spotifyPlaylist.data), \93 # spotifySecret=form.make_optional(spotifySecret.data), sttapiCheckbox=make_optional(form.sttapiCheckbox.data), \94 # stthintCheckbox=make_optional(form.stthintCheckbox.data), artistAlbumTracks=make_optional(form.artistAlbumTracks.data),\95 # nbPlaylist=make_optional(form.nbPlaylist.data), nbSamples=make_optional(form.nbSamples.data))9697else :98 @socketio.on('disconnect', '/')99 def test_disconnect():100 print('Client disconnected')101102 @app.route('/', methods=['GET', 'POST'])103 def signup():104 '''105 is called if fieldProcessing find out 'Spotify ID' case in sqlite is not empty 106 '''107 form = UpdateForm(request.form)108109 '''
...
test_optional.py
Source:test_optional.py
...149 """150 Check that we can assign to a variable of optional type151 """152 @njit153 def make_optional(val, get_none):154 if get_none:155 ret = None156 else:157 ret = val158 return ret159 @njit160 def foo(val, run_second):161 a = make_optional(val, True)162 if run_second:163 a = make_optional(val, False)164 return a165 self.assertIsNone(foo(123, False))166 self.assertEqual(foo(231, True), 231)167 def test_optional_thru_omitted_arg(self):168 """169 Issue 1868170 """171 def pyfunc(x=None):172 if x is None:173 x = 1174 return x175 cfunc = njit(pyfunc)176 self.assertEqual(pyfunc(), cfunc())177 self.assertEqual(pyfunc(3), cfunc(3))...
fixtures.py
Source:fixtures.py
1import json2from django.urls import reverse3from django.utils.translation import ugettext_noop4from corehq.apps.fixtures.models import FixtureDataType, FixtureDataItem5from corehq.apps.locations.util import load_locs_json, location_hierarchy_config6from corehq.apps.reports.filters.base import BaseReportFilter7class AsyncDrillableFilter(BaseReportFilter):8 # todo: add documentation9 # todo: cleanup template10 """11 example_hierarchy = [{"type": "state", "display": "name"},12 {"type": "district", "parent_ref": "state_id", "references": "id", "display": "name"},13 {"type": "block", "parent_ref": "district_id", "references": "id", "display": "name"},14 {"type": "village", "parent_ref": "block_id", "references": "id", "display": "name"}]15 """16 template = "reports/filters/drillable_async.html"17 hierarchy = [] # a list of fixture data type names that representing different levels of the hierarchy. Starting with the root18 def fdi_to_json(self, fdi):19 return {20 'fixture_type': fdi.data_type_id,21 'fields': fdi.fields_without_attributes,22 'id': fdi.get_id,23 'children': getattr(fdi, '_children', None),24 }25 fdts = {}26 def data_types(self, index=None):27 if not self.fdts:28 self.fdts = [FixtureDataType.by_domain_tag(self.domain, h["type"]).one() for h in self.hierarchy]29 return self.fdts if index is None else self.fdts[index]30 @property31 def api_root(self):32 return reverse('api_dispatch_list', kwargs={'domain': self.domain,33 'resource_name': 'fixture_internal',34 'api_name': 'v0.5'})35 @property36 def full_hierarchy(self):37 ret = []38 for i, h in enumerate(self.hierarchy):39 new_h = dict(h)40 new_h['id'] = self.data_types(i).get_id41 ret.append(new_h)42 return ret43 def generate_lineage(self, leaf_type, leaf_item_id):44 leaf_fdi = FixtureDataItem.get(leaf_item_id)45 index = None46 for i, h in enumerate(self.hierarchy[::-1]):47 if h["type"] == leaf_type:48 index = i49 if index is None:50 raise Exception(51 "Could not generate lineage for AsyncDrillableFilter due to a nonexistent leaf_type (%s)" % leaf_type)52 lineage = [leaf_fdi]53 for i, h in enumerate(self.full_hierarchy[::-1]):54 if i < index or i >= len(self.hierarchy)-1:55 continue56 real_index = len(self.hierarchy) - (i+1)57 lineage.insert(0, FixtureDataItem.by_field_value(self.domain, self.data_types(real_index - 1),58 h["references"], lineage[0].fields_without_attributes[h["parent_ref"]]).one())59 return lineage60 @property61 def filter_context(self):62 root_fdis = [self.fdi_to_json(f) for f in FixtureDataItem.by_data_type(self.domain, self.data_types(0).get_id)]63 f_id = self.request.GET.get('fixture_id', None)64 selected_fdi_type = f_id.split(':')[0] if f_id else None65 selected_fdi_id = f_id.split(':')[1] if f_id else None66 if selected_fdi_id:67 index = 068 lineage = self.generate_lineage(selected_fdi_type, selected_fdi_id)69 parent = {'children': root_fdis}70 for i, fdi in enumerate(lineage[:-1]):71 this_fdi = [f for f in parent['children'] if f['id'] == fdi.get_id][0]72 next_h = self.hierarchy[i+1]73 this_fdi['children'] = [self.fdi_to_json(f) for f in FixtureDataItem.by_field_value(self.domain,74 self.data_types(i+1), next_h["parent_ref"], fdi.fields_without_attributes[next_h["references"]])]75 parent = this_fdi76 return {77 'api_root': self.api_root,78 'control_name': self.label,79 'control_slug': self.slug,80 'selected_fdi_id': selected_fdi_id,81 'fdis': json.dumps(root_fdis),82 'hierarchy': self.full_hierarchy83 }84class AsyncLocationFilter(BaseReportFilter):85 # todo: cleanup template86 label = ugettext_noop("Location")87 slug = "location_async"88 template = "reports/filters/location_async.html"89 make_optional = False90 auto_drill = True91 @property92 def api_root(self):93 return reverse('api_dispatch_list', kwargs={'domain': self.domain,94 'resource_name': 'location_internal',95 'api_name': 'v0.5'})96 def load_locations_json(self, loc_id):97 return load_locs_json(self.domain, loc_id, user=self.request.couch_user)98 @property99 def location_hierarchy_config(self):100 return location_hierarchy_config(self.domain)101 @property102 def filter_context(self):103 api_root = self.api_root104 user = self.request.couch_user105 loc_id = self.request.GET.get('location_id')106 if not loc_id:107 domain_membership = user.get_domain_membership(self.domain)108 if domain_membership:109 loc_id = domain_membership.location_id110 return {111 'api_root': api_root,112 'control_name': self.label, # todo: cleanup, don't follow this structure113 'control_slug': self.slug, # todo: cleanup, don't follow this structure114 'auto_drill': self.auto_drill,115 'loc_id': loc_id,116 'locations': self.load_locations_json(loc_id),117 'make_optional': self.make_optional,118 'hierarchy': self.location_hierarchy_config119 }120 @classmethod121 def get_value(cls, request, domain):122 return request.GET.get('location_id')123class OptionalAsyncLocationFilter(AsyncLocationFilter):124 """125 This is the same as the AsyncLocationFilter, only when the template is126 rendered, it will give the user the option of filtering by location or127 not. If the user chooses to not filter by location, the location_id128 value will be blank.129 """130 make_optional = True131class MultiLocationFilter(AsyncDrillableFilter):...
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!