Best Python code snippet using playwright-python
test_element.py
Source:test_element.py
...40 self.assertTrue(e._to_html.called)41 def test_get_libraries(self):42 self.assertIsNone(Element().get_libraries())43class AsElementTestCase(unittest.TestCase):44 def test_as_element(self):45 class MyClass(object):46 pass47 class MyElement(Element):48 def __init__(self, obj):49 self.obj = obj50 # e: Element -> e51 e = Element()52 self.assertIs(as_element(e), e)53 # s: str -> HTML(s)54 s = 'raw html'55 e = as_element(s)56 self.assertIsInstance(e, HTML)57 self.assertEqual(e.content, s)58 # o: MyClass {__html__: () -> str} -> MagicHTML(o)59 o = MyClass()60 o.__html__ = lambda: 'magic html'61 e = as_element(o)62 self.assertIsInstance(e, MagicHTML)63 self.assertIs(e.obj, o)64 # o: MyClass -> TypeError65 o = MyClass()66 with pytest.raises(67 TypeError, match='Cannot convert a `MyClass` object into '68 '`Element`: no conversion function is '69 'registered'):70 _ = as_element(o)71 # register the conversion function for MyClass72 register_as_element(MyClass, lambda o: MyElement(o))73 # o: MyClass -> MyElement(o)74 o = MyClass()75 e = as_element(o)76 self.assertIsInstance(e, MyElement)77 self.assertIs(e.obj, o)78 # o: MyClass {__html__: () -> str} -> MyElement(o)79 o = MyClass()80 o.__html__ = lambda: 'magic html'81 e = as_element(o)82 self.assertIsInstance(e, MyElement)83 self.assertIs(e.obj, o)84 def test_register_as_element(self):85 with pytest.raises(86 TypeError, match='`typ_` must be a class'):87 register_as_element(1, lambda x: Element())88class NamedElementTestCase(unittest.TestCase):89 def test_name_error(self):90 self.assertIsNone(NamedElement().name)91 self.assertEqual(NamedElement('my-name').name, 'my-name')92 with pytest.raises(93 ValueError, match='`name` must be a non-empty string matching '94 'pattern'):95 _ = NamedElement('')96 with pytest.raises(97 ValueError, match='`name` must be a non-empty string matching '98 'pattern'):99 _ = NamedElement('?abc')100class TextElementsTestCase(unittest.TestCase):101 def test_text(self):102 e = Text('1&<>')103 self.assertEqual(e.text, '1&<>')104 self.assertEqual(e.to_html(), '1&<>')105 def test_html(self):106 e = HTML('1&<>')107 self.assertEqual(e.content, '1&<>')108 self.assertEqual(e.to_html(), '1&<>')109 def test_magic_html(self):110 def __html__():111 counter[0] += 1112 return str(counter[0])113 counter = [0]114 obj = Mock(__html__=__html__)115 # test not cached116 e = MagicHTML(obj, cacheable=False)117 self.assertIs(e.obj, obj)118 self.assertFalse(e.cacheable)119 self.assertEqual(e.to_html(), '1')120 self.assertEqual(e.to_html(), '2')121 # test cached122 e = MagicHTML(obj, cacheable=True)123 self.assertTrue(e.cacheable)124 self.assertEqual(e.to_html(), '3')125 self.assertEqual(e.to_html(), '3')126 # test default is not cached127 self.assertFalse(MagicHTML(obj).cacheable)128 def test_inline_math(self):129 e = InlineMath('1 & 2')130 self.assertEqual(e.mathjax, '1 & 2')131 self.assertEqual(e.get_libraries(), [MathJax()])132 self.assertEqual(133 e.to_html(),134 '<span class="inline-math">\\(1 & 2\\)</span>'135 )136 with pytest.raises(ValueError, match='`mathjax` must not be empty'):137 _ = InlineMath('')138 def test_block_math(self):139 e = BlockMath('1 & 2')140 self.assertEqual(e.mathjax, '1 & 2')141 self.assertEqual(e.get_libraries(), [MathJax()])142 self.assertEqual(143 e.to_html(),144 '<div class="block-math">$$1 & 2$$</div>'145 )146 with pytest.raises(ValueError, match='`mathjax` must not be empty'):147 _ = BlockMath('')148class ResourceElementsTestCase(unittest.TestCase):149 def test_guess_extension(self):150 self.assertEqual(Resource.guess_extension('image/png'), '.png')151 self.assertEqual(Resource.guess_extension('image/jpeg'), '.jpg')152 self.assertEqual(Resource.guess_extension('image/bmp'), '.bmp')153 self.assertEqual(Resource.guess_extension('text/csv'), '.csv')154 self.assertEqual(Resource.guess_extension('text/plain'), '.txt')155 self.assertEqual(Resource.guess_extension('text/html'), '.htm')156 self.assertEqual(Resource.guess_extension('application/octet-stream'),157 '.bin')158 self.assertIsNone(Resource.guess_extension(159 'this-ridiculous-mime-type-should-never-exist/i-am-sure'))160 # test upper case161 self.assertEqual(Resource.guess_extension('IMAGE/PNG'), '.png')162 def test_guess_mime_type(self):163 self.assertEqual(Resource.guess_mime_type('.png'), 'image/png')164 self.assertEqual(Resource.guess_mime_type('.jpg'), 'image/jpeg')165 self.assertEqual(Resource.guess_mime_type('.jpeg'), 'image/jpeg')166 self.assertEqual(Resource.guess_mime_type('.bmp'), 'image/bmp')167 self.assertEqual(Resource.guess_mime_type('.csv'), 'text/csv'),168 self.assertEqual(Resource.guess_mime_type('.txt'), 'text/plain')169 self.assertEqual(Resource.guess_mime_type('.htm'), 'text/html')170 self.assertEqual(Resource.guess_mime_type('.html'), 'text/html')171 self.assertEqual(Resource.guess_mime_type('.bin'),172 'application/octet-stream')173 self.assertIsNone(Resource.guess_mime_type(174 '.this-ridiculous-extension-should-never-exist-i-am-sure'))175 # test upper case176 self.assertEqual(Resource.guess_mime_type('.PNG'), 'image/png')177 # test error178 with pytest.raises(179 ValueError, match=r'`extension` must start with "."'):180 _ = Resource.guess_mime_type('no-leading-dot')181 def test_resource(self):182 ctx = ToHtmlContext()183 e = Resource(b'123', 'text/plain')184 self.assertEqual(e.data, b'123')185 self.assertEqual(e.mime_type, 'text/plain')186 self.assertIsNone(e.title)187 self.assertEqual(e.get_uri(ctx), 'data:text/plain;base64,MTIz')188 e2 = Resource(b'123', 'text/plain', title='456')189 self.assertEqual(e2.title, '456')190 self.assertEqual(e2.get_uri(ctx), 'data:text/plain;base64,MTIz')191 with pytest.raises(TypeError, match='`data` must be binary'):192 _ = Resource(six.text_type('123'), 'text/plain')193 def test_attachment(self):194 ctx = ToHtmlContext()195 # without title196 e = Attachment(b'123', 'text/plain')197 self.assertEqual(198 e.to_html(ctx),199 '<div class="attachment block"><span>Attachment</span>'200 '<a download="Attachment.txt" href="' + e.get_uri(ctx) +201 '">Download</a></div>'202 )203 # with title204 e = Attachment(b'123', 'text/plain', title='1 & 2')205 self.assertEqual(206 e.to_html(ctx),207 '<div class="attachment block"><span>1 & 2</span>'208 '<a download="1 & 2.txt" href="' + e.get_uri(ctx) +209 '">Download</a></div>'210 )211class ImageTestCase(unittest.TestCase):212 def test_image(self):213 ctx = ToHtmlContext()214 # without title215 e = Image(b'123', 'image/png')216 self.assertFalse(e.inline)217 self.assertEqual(218 e.to_html(ctx),219 '<img src="' + e.get_uri(ctx) + '" class="block" />'220 )221 # with title222 e = Image(b'123', 'image/png', title='1 & 2')223 self.assertFalse(e.inline)224 self.assertEqual(225 e.to_html(ctx),226 '<img src="' + e.get_uri(ctx) + '" title="1 & 2" '227 'class="block" />'228 )229 # inline image230 e = Image(b'123', 'image/png', inline=True)231 self.assertTrue(e.inline)232 self.assertEqual(233 e.to_html(ctx),234 '<img src="' + e.get_uri(ctx) + '" />'235 )236 def test_from_image(self):237 @contextlib.contextmanager238 def open_data(data):239 with BytesIO(data) as f:240 yield PILImage.open(f)241 im = PILImage.new('RGB', (1, 1), 'red')242 # test :meth:`from_image` with default format243 e = Image.from_image(im)244 with open_data(e.data) as im2: # type: PILImage.Image245 self.assertEqual(im2.format, 'PNG')246 self.assertEqual(im2.tobytes(), b'\xff\x00\x00')247 self.assertEqual(e.mime_type, 'image/png')248 # test :meth:`from_image` with 'BMP' format249 e = Image.from_image(im, format='BMP')250 with open_data(e.data) as im2: # type: PILImage.Image251 self.assertEqual(im2.format, 'BMP')252 self.assertEqual(im2.tobytes(), b'\xff\x00\x00')253 self.assertEqual(e.mime_type, 'image/bmp')254 # test :meth:`from_image` with title255 e = Image.from_image(im, title='456')256 self.assertEqual(e.title, '456')257 # test error image type258 with pytest.raises(259 TypeError, match='`image` must be an instance of '260 '`PIL.Image`'):261 _ = Image.from_image(1)262 # test error format263 with pytest.raises(264 ValueError, match='Image format \'BIN\' is not allowed'):265 _ = Image.from_image(im, 'BIN')266 # test as_element267 e = as_element(im)268 self.assertIsInstance(e, Image)269 with open_data(e.data) as im2: # type: PILImage.Image270 self.assertEqual(im2.format, 'PNG')271 self.assertEqual(im2.tobytes(), b'\xff\x00\x00')272 def test_from_figure(self):273 @contextlib.contextmanager274 def open_data(data):275 with BytesIO(data) as f:276 yield PILImage.open(f)277 # create the test figure278 fig = plt.figure(dpi=120)279 x = np.arange(0, np.pi * 2, 1001)280 y = np.sin(x)281 plt.plot(x, y)282 # test default settings283 e = Image.from_figure(fig, title='figure title')284 self.assertEqual(e.mime_type, 'image/png')285 self.assertEqual(e.title, 'figure title')286 with open_data(e.data) as im:287 self.assertEqual(im.format, 'PNG')288 default_size = im.size289 # test override dpi290 e = Image.from_figure(fig, dpi=300)291 with open_data(e.data) as im:292 self.assertNotEqual(im.size, default_size)293 # test override bbox-inches294 e = Image.from_figure(fig, tight_bbox=False)295 with open_data(e.data) as im:296 self.assertNotEqual(im.size, default_size)297 # test type error298 with pytest.raises(299 TypeError, match='`figure` must be an instance of '300 '`matplotlib.pyplot.Figure`'):301 _ = e.from_figure(1)302 # test as_element303 e = as_element(fig)304 self.assertIsInstance(e, Image)305class DataFrameTableTestCase(unittest.TestCase):306 def test_data_frame_table(self):307 df = pd.DataFrame(308 data={'a': np.arange(2) + 10, 'b': np.arange(2) + 20},309 index=np.arange(2)310 )311 e = DataFrameTable(df)312 self.assertIs(e.data_frame, df)313 s = re.sub(r'^<table[^<>]*>', '<table class="dataframe">', df.to_html())314 self.assertEqual(315 e.to_html(),316 '<div class="block">' + s + '</div>'317 )...
__init__.py
Source:__init__.py
...30 models.DescriptionField: DescriptionField,31 }32 field_view_class = mapping[field.__class__]33 return field_view_class(field, request)34 def as_element(self):35 form_container = Div()36 form_container.append(H1(self.form.title))37 form_container.append(Div(self.form.description))38 row = Div(class_=["a"])39 form = Form(row)40 size = len(self.fields)41 for i in range(size):42 current = self.fields[i]43 previous = i > 0 and self.fields[i - 1] or None44 row.append(current.as_element())45 form.append(Button("æ交", class_=["btn", "btn-primary"]))46 form_container.append(form)47 return form_container48class OptionView:49 def __init__(self, field, field_view, option, request):50 self.field = field51 self.field_view = field_view52 self.option = option53 self.request = request54 @property55 def id(self):56 return "%d_%d" % (self.field.id, self.option.value)57 @property58 def name(self):59 if "checkbox" == self.field.type:60 name = "%d[]" % (self.field.id)61 else:62 name = "%d" % (self.field.id,)63 return name64 @property65 def checked(self):66 get_value = "checkbox" == self.field.type and self.request.getlist or self.request.get67 checked_values = get_value(self.name)68 if not checked_values:69 return False70 for checked_value in checked_values:71 if int(checked_value) == self.option.value:72 return True73 return False74 @property75 def class_(self):76 input_classes = ["form-check-input"]77 if self.field.has_errors:78 input_classes.append("is-invalid")79 return input_classes80 @property81 def value(self):82 return {83 "value": self.option.value,84 "text": self.text,85 }86 @property87 def text(self):88 return self.request.get("text_%d" % self.option.id)89 def as_element(self) -> Div:90 kwargs = {}91 if self.checked:92 kwargs["checked"] = "checked"93 opt_element = [94 Input(95 class_=self.class_,96 type=self.field.type,97 name=self.name,98 id=self.id,99 value=str(self.option.value),100 **kwargs,101 ),102 Label(self.option.label, class_=["form-check-label"], for_=self.id),103 ]104 if self.option.editable:105 id_or_name = "text_%d" % self.option.id106 opt_element.append(107 Input(class_=['form-control'], id=id_or_name, name=id_or_name, value=self.text)108 )109 opt = Div(110 *opt_element,111 class_=["form-check", "form-check-inline"]112 )113 return opt114class FieldView:115 def __init__(self, field, request):116 self.field = field117 self.request = request118class DescriptionField(FieldView):119 @property120 def value(self):121 return None122 def as_element(self):123 children = [124 Label(self.field.title),125 Div(self.field.description)126 ]127 return Div(128 Div(*children,129 class_=["form-group", "col-md-12"]),130 class_=["form-row"]131 )132class TextFieldView(FieldView):133 @property134 def value(self):135 if self.field.bind_parameter:136 v = self.request.get(self.field.bind_parameter)137 else:138 v = self.request.get("%d" % self.field.id)139 return self.field.format(v)140 @property141 def class_(self):142 input_classes = ["form-control"]143 if self.field.has_errors:144 input_classes.append("is-invalid")145 return input_classes146 @property147 def id(self):148 return str(self.field.id)149 def as_element(self):150 if self.field.multiple:151 input = TextArea(152 self.value,153 class_=self.class_,154 id=self.id,155 name=self.id,156 placeholder=self.field.placeholder157 )158 else:159 input = Input(type="text",160 class_=self.class_,161 id=self.id,162 name=self.id,163 value=self.value,164 placeholder=self.field.placeholder165 )166 if self.field.readonly:167 input.disabled = "disabled"168 children = [169 Label(self.field.title, for_=self.id),170 input171 ]172 if self.field.has_errors:173 children.append(174 Div(*[Li(str(e)) for e in self.field.errors], class_=["invalid-feedback"])175 )176 return Div(177 Div(*children,178 class_=["form-group", "col-md-12"]),179 class_=["form-row"]180 )181class PhoneFieldView(TextFieldView):182 pass183class SelectFieldView(FieldView):184 def __init__(self, field, request):185 super().__init__(field, request)186 self._assemble_options()187 def _assemble_options(self):188 self.options = []189 for opt in self.field.options:190 option_view = OptionView(self.field, self, opt, self.request)191 self.options.append(option_view)192 @property193 def value(self):194 return self.field.format([opt.value for opt in self.options if opt.checked])195 def as_element(self):196 input_classes = ["of-form-title"]197 if self.field.has_errors:198 input_classes.append("is-invalid")199 options = [200 Label(self.field.title, for_=str(self.field.id), class_=input_classes)201 ]202 for opt in self.options:203 options.append(opt.as_element())204 if self.field.has_errors:205 options.append(206 Div(*[Li(str(e)) for e in self.field.errors], class_=["invalid-feedback"])207 )208 return Div(209 Div(*options,210 class_=["form-group", "col-md-12"]),211 class_=["form-row"]212 )213class FormViewModelAssembler:214 def to_view_model(self, model, request):215 model.sort()216 form_view = FormView(model, request)217 return form_view
pypi_analyzer.py
Source:pypi_analyzer.py
1from contrib.elements.codeblock import Import2from contrib.elements.versions import Version3import json4import re5class PyPIAnalyzer:6 def __init__(self, basic_info: dict):7 self.basic_info = basic_info8 self.requirement_list = []9 def available_versions(self, version_str_list=None):10 if version_str_list is None:11 version_str_list = []12 if not version_str_list:13 return self.basic_info["released_versions"] \14 if "released_versions" in self.basic_info.keys() else []15 available_versions = [Version(version) for version in self.basic_info["released_versions"]]16 checked_versions = []17 symbols = ['<', '<=', '>', '>=', '==', '!=']18 versions = [[], [], [], [], [], []]19 version_dict = dict(zip(symbols, versions))20 for version_str in version_str_list:21 elements = re.findall("([!><=]+)([0-9].*)", string=version_str)[0]22 for symbol in symbols:23 if elements[0] == symbol:24 version_dict[symbol].append(Version(elements[1]))25 for version in available_versions:26 is_available = True27 for lt_version in version_dict['<']:28 if not version < lt_version:29 is_available = False30 for le_version in version_dict['<=']:31 if not version <= le_version:32 is_available = False33 for mt_version in version_dict['>']:34 if not version > mt_version:35 is_available = False36 for me_version in version_dict['>=']:37 if not version >= me_version:38 is_available = False39 for eq_version in version_dict['==']:40 if not version == eq_version:41 is_available = False42 for ne_version in version_dict['!=']:43 if not version != ne_version:44 is_available = False45 if is_available:46 checked_versions.append(version)47 return [version.version_str for version in checked_versions]48 def parse_requirement_dist(self):49 requirements_list = self.basic_info["requires_dist"] \50 if "requires_dist" in self.basic_info.keys() else []51 if not requirements_list:52 return []53 parsed_requirements_list = []54 for requirement in requirements_list:55 requirement_index = requirement.find(';')56 parsed_requirement = requirement57 if requirement_index != -1:58 parsed_requirement = requirement[:requirement_index].strip()59 parsed_requirements_list.append(parsed_requirement)60 parsed_requirements_imports = []61 for parsed_requirement in parsed_requirements_list:62 elements = re.findall(63 "(.+)\[(.+)] \((.+)\)", parsed_requirement)64 if elements:65 for element in elements:66 parsed_requirements_imports.append(67 Import(name=element[0].strip(),68 filename=self.basic_info["name"],69 line=-1,70 from_element=element[0].strip(),71 import_element="*",72 as_element=element[0].strip(),73 version=element[2].strip()74 )75 )76 continue77 elements = re.findall(78 "(.+) \((.+)\)", parsed_requirement)79 if elements:80 for element in elements:81 parsed_requirements_imports.append(82 Import(name=element[0].strip(),83 filename=self.basic_info["name"],84 line=-1,85 from_element=element[0].strip(),86 import_element="*",87 as_element=element[0].strip(),88 version=element[1].strip()89 )90 )91 continue92 elements = re.findall(93 "([a-zA-Z_-]+)([><=!~][><=,!~. ]*)", parsed_requirement.replace(" ", "")94 )95 if elements:96 for element in elements:97 parsed_requirements_imports.append(98 Import(name=element[0].strip(),99 filename=self.basic_info["name"],100 line=-1,101 from_element=element[0].strip(),102 import_element="*",103 as_element=element[0].strip(),104 version=element[1].replace(" ", "")105 )106 )107 continue108 elements = re.findall(109 "(.+)\[(.+)]", parsed_requirement)110 if elements:111 for element in elements:112 parsed_requirements_imports.append(113 Import(name=element[0].strip(),114 filename=self.basic_info["name"],115 line=-1,116 from_element=element[0].strip(),117 import_element="*",118 as_element=element[0].strip(),119 version="*"120 )121 )122 continue123 parsed_requirements_imports.append(124 Import(name=parsed_requirement.strip(),125 filename=self.basic_info["name"],126 line=-1,127 from_element=parsed_requirement.strip(),128 import_element="*",129 as_element=parsed_requirement.strip(),130 version='*'131 )132 )133 self.requirement_list = parsed_requirements_imports134 return parsed_requirements_list135if __name__ == "__main__":136 package_names = ['django', 'pip', 'requests']137 for package_name in package_names:138 path = './output/%s/' % package_name139 requirement_simple_filename = path + 'requirement-simple.json'140 with open(requirement_simple_filename) as f:141 print("[pypi_analyzer]Open file: %s" % requirement_simple_filename)142 result = json.load(f)143 # print(result)144 analyzer = PyPIAnalyzer(result)145 print("[pypi_analyzer]Available versions:")146 print(analyzer.available_versions([]))147 print("[pypi_analyzer]parse_requirement_dist:")...
find.py
Source:find.py
1"""Virtuoso driver: Find entities in the graph database2The UWKGM project3:copyright: (c) 2020 Ichise Laboratory at NII & AIST4:author: Rungsiman Nararatwong5"""6from typing import Dict, List, Union7from database.drivers.graph.virtuoso import client8def candidates(graph: str, label: str, limit: Union[int, None], language: str, query_limit: int, perfect_match_only: bool) -> \9 Dict[str, List[Dict[str, Union[str, List[str]]]]]:10 """Finds candidates of entities given a partial or full label"""11 def fetch(perfect_match: bool):12 if perfect_match:13 terms = ['"%s"' % term for term in label.strip().split(' ')]14 else:15 # Each word in the search term needs at least four characters to be included in partial search16 # The asterisk (*) indicates partial search17 terms = ['"%s*"' % term if len(term) > 3 else '"%s"' % term for term in label.strip().split(' ')]18 # Search terms are joined by 'AND' operators19 client.setQuery('SELECT DISTINCT ?entity, ?label, ?type FROM <%s> WHERE {'20 '?entity <http://www.w3.org/2000/01/rdf-schema#label> ?label ; a ?type .'21 '?label bif:contains \'%s\' %s} %s' % (graph, ' and '.join(terms), language_filter, limit_filter))22 return client.query().convert()['results']['bindings']23 language_filter = "FILTER (lang(?label) = '%s')" % language if language is not None and len(language) else ''24 limit_filter = "LIMIT %d" % query_limit if query_limit is not None else ''25 matches = dict()26 # Try searching for perfect matches first since perfect-match search is the fastest due to indexing27 response = fetch(True)28 # If not perfect matches found, try partial matches29 if len(response) == 0 and not perfect_match_only:30 response = fetch(False)31 # Convert the response into a clean dictionary-based output32 for item in response:33 entity, entity_label, entity_types = item['entity']['value'], item['label']['value'], item['type']['value'] if 'type' in item else []34 if entity not in matches:35 matches[entity] = {'label': entity_label, 'types': [entity_types]}36 else:37 matches[entity]['types'].append(entity_types)38 results = {'exact_matches': [], 'first_matches': [], 'partial_matches': []}39 # Categorizes matches in to 'exact', 'first', and 'partial' lists40 for entity, data in matches.items():41 search = label.lower()42 entity_label = data['label'].lower()43 if search == entity_label:44 results['exact_matches'].append((len(entity_label), {'entity': entity, **data}))45 elif entity_label.startswith(search):46 results['first_matches'].append((len(entity_label), {'entity': entity, **data}))47 else:48 results['partial_matches'].append((len(entity_label), {'entity': entity, **data}))49 # Return matches with shorter labels first50 results['exact_matches'].sort(key=lambda x: x[0])51 results['first_matches'].sort(key=lambda x: x[0])52 results['partial_matches'].sort(key=lambda x: x[0])53 if limit is not None:54 return {'exact_matches': [entity[1] for entity in results['exact_matches'][:limit]],55 'first_matches': [entity[1] for entity in results['first_matches'][:limit - len(results['first_matches'])]],56 'partial_matches': [entity[1] for entity in57 results['partial_matches'][:limit - len(results['first_matches']) - len(results['partial_matches'])]]}58 else:59 return {'exact_matches': [entity[1] for entity in results['exact_matches']],60 'first_matches': [entity[1] for entity in results['first_matches']],61 'partial_matches': [entity[1] for entity in results['partial_matches']]}62def single(graph: str, entity: str, as_element: Union[str, None], limit: int) -> Dict[str, List[Dict[str, str]]]:63 """Finds triples which the given entity is a part of (as subject, predicate, object, or any)"""64 results = {'subject': None, 'predicate': None, 'object': None}65 if as_element is None or as_element == 'subject':66 client.setQuery('SELECT DISTINCT ?predicate ?predicateLabel ?object ?objectLabel FROM <%s> WHERE {'67 '<%s> ?predicate ?object '68 'OPTIONAL { ?predicate <http://www.w3.org/2000/01/rdf-schema#label> ?predicateLabel } '69 'OPTIONAL { ?object <http://www.w3.org/2000/01/rdf-schema#label> ?objectLabel } '70 '}' % (graph, entity))71 results['subject'] = client.query().convert()['results']['bindings'][:limit]72 if as_element is None or as_element == 'predicate':73 client.setQuery('SELECT DISTINCT ?subject ?subjectLabel ?object ?objectLabel WHERE {'74 '?subject <%s> ?object '75 'OPTIONAL { ?subject <http://www.w3.org/2000/01/rdf-schema#label> ?subjectLabel } '76 'OPTIONAL { ?object <http://www.w3.org/2000/01/rdf-schema#label> ?objectLabel } '77 '}' % entity)78 results['predicate'] = client.query().convert()['results']['bindings'][:limit]79 if as_element is None or as_element == 'object':80 client.setQuery('SELECT DISTINCT ?subject ?subjectLabel ?predicate ?predicateLabel WHERE {'81 '?subject ?predicate <%s> '82 'OPTIONAL { ?subject <http://www.w3.org/2000/01/rdf-schema#label> ?subjectLabel } '83 'OPTIONAL { ?predicate <http://www.w3.org/2000/01/rdf-schema#label> ?predicateLabel } '84 '}' % entity)85 results['object'] = client.query().convert()['results']['bindings'][:limit]86 return results87# def relations(source: str, targets: List[str]) -> Dict[str, List[Dict[str, str]]]:88# results = dict()89#90# for target in targets:91# client.setQuery('SELECT DISTINCT ?sourcePredicate ?targetPredicate ?object ?label WHERE {'92# '<%s> ?sourcePredicate ?object . <%s> ?targetPredicate ?object . '93# '?object <http://www.w3.org/2000/01/rdf-schema#label> ?label }' % (source, target))94#95# result = client.query().convert()['results']['bindings']96# results[target] = result97#...
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!!