-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
1125 lines (1037 loc) · 42.6 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from ast import Str
from importlib.metadata import requires
import itertools
from operator import truediv
import os
from pathlib import Path
from socket import timeout
import ssl
from typing import Dict
from xml.dom.minidom import Document, parseString
from xml.dom.minidom import parseString
from SPARQLWrapper import *
from SPARQLWrapper import SPARQLWrapper
import requests
import time
import mechanize
from twill.commands import browser
import query
from Resources import Resources
from ExternalLink import ExternalLink
import networkx as nx
import re
import validators
import shutil
import urllib.request
from urllib.parse import urlparse
import json
import ssl
#PRINT THE METADATI OF A KG
def printMetadatiKG(metadct):
for key, value in metadct.items() :
print (key, value)
#PRINT THE KGs
def printKGs(kgs):
print(*kgs, sep = "\n \n \n")
#PRINT KGs WITH NAME AND DESCRIPTION
def printNameKGs(kgs):
for x in range(len(kgs)):
element = kgs[x]
name = element.get('title')
description = element.get('description')
print('Name: %s \nDescription: %s \n \n' %(name, description))
def getNameKG(kg):
name = kg.get('title')
return name
def getIdKG(metadata):
id = metadata.get('id')
return id
def getResultsFromJSON(results):
result = results.get('results')
bindings = result.get('bindings')
if isinstance(bindings,list):
resultsList = []
for i in range(len(bindings)):
object = bindings[i].get('o')
if isinstance(object,dict):
value = object.get('value')
if (not value == ''):
resultsList.append(value)
return resultsList
else:
return False
def getResultsFromJSONo(results):
result = results.get('results')
bindings = result.get('bindings')
if isinstance(bindings,list):
resultsList = []
for i in range(len(bindings)):
object = bindings[i].get('o')
if isinstance(object,dict):
value = object.get('value')
resultsList.append(value)
return resultsList
else:
return False
def getResultsFromJSONp(results):
result = results.get('results')
bindings = result.get('bindings')
if isinstance(bindings,list):
resultsList = []
for i in range(len(bindings)):
object = bindings[i].get('p')
if isinstance(object,dict):
value = object.get('value')
resultsList.append(value)
return resultsList
else:
return False
def getResultsFromJSONs(results):
result = results.get('results')
bindings = result.get('bindings')
if isinstance(bindings,list):
resultsList = []
for i in range(len(bindings)):
object = bindings[i].get('s')
if isinstance(object,dict):
value = object.get('value')
if (not value == ''):
resultsList.append(value)
return resultsList
else:
return False
def getResultsFromJSONMin(results):
result = results.get('results')
bindings = result.get('bindings')
if isinstance(bindings,list):
resultsList = []
for i in range(len(bindings)):
object = bindings[i].get('min')
if isinstance(object,dict):
value = object.get('value')
if (not value == ''):
resultsList.append(value)
return resultsList
else:
return False
def getResultsFromJSONMax(results):
result = results.get('results')
bindings = result.get('bindings')
if isinstance(bindings,list):
resultsList = []
for i in range(len(bindings)):
object = bindings[i].get('max')
if isinstance(object,dict):
value = object.get('value')
if (not value == ''):
resultsList.append(value)
return resultsList
else:
return False
def getResultsFromJSONCount(results):
result = results.get('results')
bindings = result.get('bindings')
if isinstance(bindings,list):
resultsList = []
for i in range(len(bindings)):
object = bindings[i].get('triples')
if isinstance(object,dict):
value = object.get('value')
if (not value == ''):
resultsList.append(value)
return resultsList
else:
return False
def getResultsFromJSONCountInt(results):
result = results.get('results')
bindings = result.get('bindings')
if isinstance(bindings,list):
resultsList = []
for i in range(len(bindings)):
object = bindings[i].get('triples')
if isinstance(object,dict):
value = object.get('value')
if (not value == ''):
return int(value)
else:
return 'absent'
else:
return False
def getResultsFromJSONCountIntT(results):
result = results.get('results')
bindings = result.get('bindings')
if isinstance(bindings,list):
resultsList = []
for i in range(len(bindings)):
object = bindings[i].get('t')
if isinstance(object,dict):
value = object.get('value')
if (not value == ''):
return int(value)
else:
return 'absent'
else:
return False
def getResultsFromXML(results):
if isinstance(results,Document): #IF RESULT IS IN XML
li = []
literalList = results.getElementsByTagName('literal')
numTags = results.getElementsByTagName("literal").length
for i in range(numTags):
if literalList[i].firstChild is not None:
literal = literalList[i].firstChild.nodeValue
li.append(literal)
literalList = results.getElementsByTagName('uri')
numTags = results.getElementsByTagName("uri").length
for i in range(numTags):
if literalList[i].firstChild is not None:
literal = literalList[i].firstChild.nodeValue
li.append(literal)
return li
def getResultsFromXMLUri(results):
if isinstance(results,Document): #IF RESULT IS IN XML
li = []
literalList = results.getElementsByTagName('uri')
numTags = results.getElementsByTagName("uri").length
for i in range(numTags):
if literalList[i].firstChild is not None:
literal = literalList[i].firstChild.nodeValue
li.append(literal)
return li
def getResultsFromXMLCount(results):
if isinstance(results,Document):
numTags = results.getElementsByTagName("binding").length
if numTags > 0:
desc = results.getElementsByTagName("binding")[0]
triples = desc.getElementsByTagName("literal")
triplesValue = triples[0].firstChild.nodeValue
return (int(triplesValue))
else:
return False
#GET SPARQL ENDPOINT OF A GIVEN SET OF METADATI
def getSparqlEndPoint(metadati):
sparqlInfo = metadati.get('sparql')
if not sparqlInfo:
accessUrl = ''
return accessUrl
accessUrl = sparqlInfo.get('access_url')
return accessUrl
def prettyPrintXML(xml):
xml_pretty_str = xml.toprettyxml()
print (xml_pretty_str)
def checkRedirect(url):
if url:
try:
br = mechanize.Browser() #NECESSARIO PER RISOLVERE IL PROBLEMA DI REINDIRIZZAMENTO NEL CASO L'ENDPOINT E' STATO SPOSTATO
br.set_handle_robots(False)
#br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
response = br.open(url)
newUrl = response.geturl()
return newUrl
except: #IF THERE IS AN EXCEPTION WE RETURN IN THE CODE BECAUSE THEY ARE ALREADY MANAGED IN THE TEST OF THE SPARQ ENDPOINT
return
else:
return
def getNumTriple(metadati):
triples = metadati.get('triples')
try:
triplesInt = int(triples)
except ValueError: #IN CASE IN THE METADATA THE VALUE IS IN THE FORMAT '1.3 million'
triplesInt = triples
return triples
def getSource(metadata):
source = metadata.get('website')
return source
def checkAvailabilityResource(url):
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.76 Safari/537.36'}
ssl.match_hostname = lambda cert, hostname: True
try:
#url = checkRedirect(url) #BEFORE CHECK IF THE URL IS REDIRECTED
response = requests.head(url,timeout=180,allow_redirects=True, verify=False) #3 MINUTES
if response.status_code < 400: #IF FAILS WITH A HEAD REQUEST, WE TEST WITH A GET (HEAD MAY NOT BE SUPPORTED)
return True
else:
response = requests.head(url,timeout=180,allow_redirects=True, verify=False)
if response.status_code < 400:
return True
else:
newUrl = response.url
if newUrl != url:
response = requests.head(newUrl,timeout=180,allow_redirects=True, verify=False)
if response.status_code < 400:
return True
else:
response = requests.head(newUrl,timeout=180,allow_redirects=True, verify=False)
if response.status_code < 400:
return True
else:
return False
except Exception as e:
return False
except requests.exceptions.SSLError as e:
print(f"SSL Error: {e}")
return False
def checkAvailabilityResourceHead(url):
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.76 Safari/537.36'}
try:
#url = checkRedirect(url) #BEFORE CHECK IF THE URL IS REDIRECTED
response = requests.head(url,timeout=120) #3 MINUTES
if response.status_code < 400: #IF FAILS WITH A HEAD REQUEST, WE TEST WITH A GET (HEAD MAY NOT BE SUPPORTED)
return True
else:
newUrl = response.url
if newUrl != url:
response = requests.head(newUrl,timeout=120)
if response.status_code < 400:
return True
else:
return False
except:
return False
def checkAvailabilityListResources(urlList):
if len(urlList) > 0:
for i in range(len(urlList)):
available = checkAvailabilityResource(urlList[i])
if available == True:
return True
return False
return False
def getActiveDumps(urlList):
url = []
if len(urlList) > 0:
for i in range(len(urlList)):
available = checkAvailabilityResource(urlList[i])
if available == True:
url.append(urlList[i])
return url
return url
def getInactiveDumps(urlList):
url = []
if len(urlList) > 0:
for i in range(len(urlList)):
available = checkAvailabilityResource(urlList[i])
if available == False:
url.append(urlList[i])
return url
return url
def mergeResources(resourcesDH,resourcesLODC):
if isinstance(resourcesDH,list) and len(resourcesDH) > 0: #MERGE THE TWO LISTS OF RESOURCES FROM DH E LODC AND DELETING DUPLICATE
found = False
for i in range(len(resourcesLODC)):
urlLODC = resourcesLODC[i].get('path')
for j in range(len(resourcesDH)): #COMPARE AN ITEM IN THE LIST OF RESOURCES FROM LOD CLOUD WITH EACH ITEM IN THE LIST OF RESOURCES FROM DATAHUB
urlDH = resourcesDH[j].get('path')
if urlLODC == urlDH:
found = True #IF THE LINK TO THE RESOURCES IS THE SAME, THEN WE DON'T ADD THE ITEM TO THE LIST
if found == False:
resourcesDH.append(resourcesLODC[i])
else:
found = False
return resourcesDH
else:
return resourcesLODC #IF IN DATAHUB THERE AREN'T RESOURCES, PRINT ONLY THE RESOURCES IN LOD CLOUD
#INPUT LIST OF RESOURCES
#OUTPUT LIST OF RESOURCES WITH A FIELD STATUS. STATUS = ACTIVE IF URL IS ONLINE, STATUS = OFFLINE IF URL IS OFFLINE
def insertAvailability(resources):
active = False
for i in range(len(resources)):
d = resources[i]
url = d.get('path')
active = checkAvailabilityResource(url)
if active == True:
d['status'] = 'active'
else:
d['status'] = 'offline'
return resources
def checkhttps(url):
if 'https' in url:
return True
else:
url = url.replace('http','https')
return query.checkEndPoint(url)
def checkAvailabilityForDownload(resources):
availability = 0
if len(resources) == 0:
availability = -1
return availability
else:
for i in range(len(resources)):
d = resources[i]
type = d.get('type')
status = d.get('status')
format = d.get('format')
if isinstance(type,str):
if type == 'full_download' and status == 'active':
availability = 1
if isinstance(format,str):
if status == 'active':
availability = 1
'''
elif status == 'offline':
availability = 0
if 'zip' in format and status == 'active':
availability = 1
elif 'zip' in format and status == 'offline':
availability = 0
if format == 'application/rdf+xml' and status == 'active':
availability = 1
elif format == 'application/rdf+xml' and status == 'offline':
availability = 0
if format == 'text/turtle' and status == 'active':
availability = 1
elif format == 'text/turtle' and status == 'offline':
availability = 0
if format == 'application/x-ntriples' and status == 'active':
availability = 1
elif format == 'application/x-ntriples' and status == 'offline':
availability = 0
if format == 'application/x-nquads' and status == 'active':
availability = 1
elif format == 'application/x-nquads' and status == 'offline':
availability = 0
if format == 'text/n3' and status == 'active':
availability = 1
elif format == 'text/n3' and status == 'offline':
availability = 0
if format == 'rdf' and status == 'active':
availability = 1
elif format == 'rdf' and status == 'offline':
availability = 0
if format == 'text/rdf+n3' and status == 'active':
availability = 1
elif format == 'text/rdf+n3' and status == 'offline':
availability = 0
if format == 'rdf/turtle' and status == 'active':
availability = 1
elif format == 'rdf/turtle' and status == 'offline':
availability = 0
'''
return availability
def getLinkDownload(resources):
urls = []
availability = False
for i in range(len(resources)):
d = resources[i]
type = d.get('type')
status = d.get('status')
format = d.get('format')
if isinstance(type,str):
if type == 'full_download' and status == 'active':
availability = True
urls.append(d.get('path'))
'''
if isinstance(format,str):
if status == 'active':
availability = True
urls.append(d.get('path'))
if 'zip' in format and status == 'active':
availability = True
urls.append(d.get('path'))
if format == 'application/rdf+xml' and status == 'active':
availability = True
urls.append(d.get('path'))
if format == 'text/turtle' and status == 'active':
availability = True
urls.append(d.get('path'))
if format == 'application/x-ntriples' and status == 'active':
availability = True
urls.append(d.get('path'))
if format == 'application/x-nquads' and status == 'active':
availability = True
urls.append(d.get('path'))
if format == 'text/n3' and status == 'active':
availability = True
urls.append(d.get('path'))
if format == 'rdf' and status == 'active':
availability = True
urls.append(d.get('path'))
if format == 'text/rdf+n3' and status == 'active':
availability = True
urls.append(d.get('path'))
if format == 'rdf/turtle' and status == 'active':
availability = True
urls.append(d.get('path'))
'''
return urls
def getLinkOfflineDump(resources):
urls = []
for i in range(len(resources)):
d = resources[i]
type = d.get('type')
status = d.get('status')
format = d.get('format')
if isinstance(type,str):
if type == 'full_download' and status == 'offline':
urls.append(d.get('path'))
if isinstance(format,str):
if 'ZIP' in format and status == 'offline':
urls.append(d.get('path'))
if 'zip' in format and status == 'offline':
urls.append(d.get('path'))
if format == 'application/rdf+xml' and status == 'offline':
urls.append(d.get('path'))
if format == 'text/turtle' and status == 'offline':
urls.append(d.get('path'))
if format == 'application/x-ntriples' and status == 'offline':
urls.append(d.get('path'))
if format == 'application/x-nquads' and status == 'offline':
urls.append(d.get('path'))
if format == 'text/n3' and status == 'offline':
urls.append(d.get('path'))
if format == 'rdf' and status == 'offline':
urls.append(d.get('path'))
if format == 'text/rdf+n3' and status == 'offline':
urls.append(d.get('path'))
if format == 'rdf/turtle' and status == 'offline':
urls.append(d.get('path'))
return urls
def toObjectResources(resourcesDH):
otResources = []
for i in range(len(resourcesDH)):
path = resourcesDH[i].get('path')
format = resourcesDH[i].get('format')
description = resourcesDH[i].get('description')
status = resourcesDH[i].get('status')
title = resourcesDH[i].get('title')
type = resourcesDH[i].get('type',None)
resource = Resources(path,title,description,status,format,type)
otResources.append(resource)
return otResources
def toObjectExternalLinks(externalLinks):
exList = []
if isinstance(externalLinks,dict):
for i in externalLinks:
key = i
value = externalLinks.get(i)
exLink = ExternalLink(key,value)
exList.append(exLink)
return exList
else:
return False
def calculatePageRank(nameKG,externalLinks):
if isinstance(externalLinks,list):
G = nx.Graph()
for i in range(len(externalLinks)):
link = externalLinks[i]
value = str(link.value)
value = re.sub("[^\d\.]", "",value)
G.add_edge(nameKG,link.nameKG,weight=value)
pr = nx.pagerank(G)
return pr.get(nameKG)
#pos = nx.spring_layout(G, k=0.8)
#nx.draw(G,pos,with_labels=True,width=0.4,node_size=400)
#pos = nx.spring_layout(G)
#nx.draw_networkx_edge_labels(G,pos)
#plt.show()
else:
return 0
def getDegreeOfConnection(nameKG,externalLinks):
if isinstance(externalLinks,list):
G = nx.Graph()
for i in range(len(externalLinks)):
link = externalLinks[i]
value = str(link.value)
value = re.sub("[^\d\.]", "",value)
G.add_edge(nameKG,link.nameKG,weight=value)
degree = G.degree(nbunch=nameKG) #ONLY THE DEGREE OF THE GRAPH WE ARE ANALYZING
return degree
def getCentrality(nameKG,externalLinks):
if isinstance(externalLinks,list):
G = nx.Graph()
for i in range(len(externalLinks)):
link = externalLinks[i]
value = str(link.value)
value = re.sub("[^\d\.]", "",value)
G.add_edge(nameKG,link.nameKG,weight=value)
degreeCentrality = nx.degree_centrality(G)
return degreeCentrality.get(nameKG)
def getClusteringCoefficient(nameKG,externalLinks):
if isinstance(externalLinks,list):
G = nx.Graph()
for i in range(len(externalLinks)):
link = externalLinks[i]
value = str(link.value)
value = re.sub("[^\d\.]", "",value)
G.add_edge(nameKG,link.nameKG,weight=value)
clusteringCoefficient = nx.clustering(G,nameKG)
return clusteringCoefficient
def getThroughput(accessUrl):
count = 0
countList = []
for i in range(10):
count = 0
start_time = time.time()
while (time.time() - start_time) < 1:
query.TPQuery(accessUrl,count)
count = count +1
countList.append(count)
return countList
def getThroughputNoOff(accessUrl):
count = 0
countList = []
for i in range(5):
count = 0
start_time = time.time()
while (time.time() - start_time) < 1:
query.checkEndPoint(accessUrl)
count = count +1
countList.append(count)
return countList
def getUrlVoID(otResources):
if isinstance(otResources,list):
for i in range(len(otResources)):
resource = otResources[i]
if resource.format is not None:
if resource.format == 'meta/void' and resource.status == 'active':
urlV = resource.url
if isinstance(urlV,str):
return urlV
elif resource.title is not None:
if 'void' in resource.title and resource.status == 'active':
urlV = resource.url
if isinstance(urlV,str):
return urlV
else:
return False
def getNumberResultsLOV(jsonFile):
if isinstance(jsonFile,dict):
totalResults = jsonFile.get('total_results')
totalResults = int(totalResults)
if totalResults > 0:
return True
else:
return False
else:
return False
def checkURI(uri):
try:
r = requests.head(uri,timeout=1)
if r.status_code == 200:
return True
else:
return False
except:
return False
def validateURI(uri):
try:
uri = uri.strip()
result = urlparse(uri)
return bool(result.scheme) and bool(result.netloc)
except ValueError:
return False
def xmlToDict(results):
dictList = []
literalList = results.getElementsByTagName("result")
for node in literalList:
alist = node.getElementsByTagName('binding')
d = {}
for node2 in alist:
if node2.getAttribute('name') == 's':
uriList = node2.getElementsByTagName('uri')
literalList = node2.getElementsByTagName('literal')
uriList = uriList+literalList
for a in uriList:
ds = {}
uri = a.firstChild.data
ds['value'] = uri
d['s'] = ds
elif node2.getAttribute('name') == 'o':
uriList2 = node2.getElementsByTagName('uri')
literalList2 = node2.getElementsByTagName('literal')
uriList2 = uriList2 + literalList2
for a in uriList2:
do = {}
obj = a.firstChild.data
do['value'] = obj
d['o'] = do
dictList.append(d)
return dictList
def xmlToDictSP(results):
dictList = []
literalList = results.getElementsByTagName("result")
for node in literalList:
alist = node.getElementsByTagName('binding')
d = {}
for node2 in alist:
if node2.getAttribute('name') == 's':
uriList = node2.getElementsByTagName('uri')
literalList = node2.getElementsByTagName('literal')
uriList = uriList+literalList
for a in uriList:
ds = {}
uri = a.firstChild.data
ds['value'] = uri
d['s'] = ds
elif node2.getAttribute('name') == 'p':
uriList2 = node2.getElementsByTagName('uri')
literalList2 = node2.getElementsByTagName('literal')
uriList2 = uriList2 + literalList2
for a in uriList2:
do = {}
obj = a.firstChild.data
do['value'] = obj
d['p'] = do
dictList.append(d)
return dictList
def xmlToDictO(results):
dictList = []
literalList = results.getElementsByTagName("result")
for node in literalList:
alist = node.getElementsByTagName('binding')
d = {}
for node2 in alist:
if node2.getAttribute('name') == 'o':
uriList = node2.getElementsByTagName('uri')
literalList = node2.getElementsByTagName('literal')
uriList = uriList+literalList
for a in uriList:
ds = {}
if a.firstChild is not None:
uri = a.firstChild.data
ds['value'] = uri
d['o'] = ds
dictList.append(d)
return dictList
def xmlToDictS(results):
dictList = []
literalList = results.getElementsByTagName("result")
for node in literalList:
alist = node.getElementsByTagName('binding')
d = {}
for node2 in alist:
if node2.getAttribute('name') == 's':
uriList = node2.getElementsByTagName('uri')
literalList = node2.getElementsByTagName('literal')
uriList = uriList+literalList
for a in uriList:
ds = {}
if a.firstChild is not None:
uri = a.firstChild.data
ds['value'] = uri
d['s'] = ds
dictList.append(d)
return dictList
def xmlToDictP(results):
dictList = []
literalList = results.getElementsByTagName("result")
for node in literalList:
alist = node.getElementsByTagName('binding')
d = {}
for node2 in alist:
if node2.getAttribute('name') == 'p':
uriList = node2.getElementsByTagName('uri')
literalList = node2.getElementsByTagName('literal')
uriList = uriList+literalList
for a in uriList:
ds = {}
if a.firstChild is not None:
uri = a.firstChild.data
ds['value'] = uri
d['p'] = ds
dictList.append(d)
return dictList
def xmlToDictSPO(results):
dictList = []
literalList = results.getElementsByTagName("result")
for node in literalList:
alist = node.getElementsByTagName('binding')
d = {}
for node2 in alist:
if node2.getAttribute('name') == 's':
uriList = node2.getElementsByTagName('uri')
literalList = node2.getElementsByTagName('literal')
uriList = uriList+literalList
for a in uriList:
ds = {}
uri = a.firstChild.data
ds['value'] = uri
d['s'] = ds
elif node2.getAttribute('name') == 'p':
uriList2 = node2.getElementsByTagName('uri')
literalList2 = node2.getElementsByTagName('literal')
uriList2 = uriList2 + literalList2
for a in uriList2:
do = {}
obj = a.firstChild.data
do['value'] = obj
d['p'] = do
elif node2.getAttribute('name') == 'o':
uriList2 = node2.getElementsByTagName('uri')
literalList2 = node2.getElementsByTagName('literal')
uriList2 = uriList2 + literalList2
for a in uriList2:
do = {}
obj = a.firstChild.data
do['value'] = obj
d['o'] = do
dictList.append(d)
return dictList
def searchString(stringList,toFind):
for i in range(len(stringList)):
if toFind in stringList[i]:
return True
return False
def getRegex(dataType):
d = {
'http://www.w3.org/2001/XMLSchema#integer' : '[\-+]?[0-9]+',
'http://www.w3.org/2001/XMLSchema#double' : '(\+|-)?([0-9]+(\.[0-9]*)?|\.[0-9]+)([Ee](\+|-)?[0-9]+)? |(\+|-)?INF|NaN',
'http://www.w3.org/2001/XMLSchema#float' : '(\+|-)?([0-9]+(\.[0-9]*)?|\.[0-9]+)([Ee](\+|-)?[0-9]+)?|(\+|-)?INF|NaN',
'http://www.w3.org/2001/XMLSchema#any' : '.*',
'http://www.w3.org/2001/XMLSchema#decimal' : '(\+|-)?([0-9]+(\.[0-9]*)?|\.[0-9]+)',
'http://www.w3.org/2001/XMLSchema#time' : '(([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\.[0-9]+)?|(24:00:00(\.0+)?))(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?',
'http://www.w3.org/2001/XMLSchema#date' : '-?([1-9][0-9]{3,}|0[0-9]{3})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?',
'http://www.w3.org/2001/XMLSchema#dateTime' : '-?([1-9][0-9]{3,}|0[0-9]{3})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])T(([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\.[0-9]+)?|(24:00:00(\.0+)?))(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?',
'http://www.w3.org/2001/XMLSchema#dateTimeStamp': '-?([1-9][0-9]{3,}|0[0-9]{3})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])T(([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\.[0-9]+)?|(24:00:00(\.0+)?))(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?.*(Z|(\+|-)[0-9][0-9]:[0-9][0-9])',
'http://www.w3.org/2001/XMLSchema#string' : '.*',
'http://www.w3.org/2001/XMLSchema#gYear' : '-?([1-9][0-9]{3,}|0[0-9]{3})(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?',
'http://www.w3.org/2001/XMLSchema#gMonth' : '--(0[1-9]|1[0-2])(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?',
'http://www.w3.org/2001/XMLSchema#gDay' : '---(0[1-9]|[12][0-9]|3[01])(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?',
'http://www.w3.org/2001/XMLSchema#gYearMonth' : '-?([1-9][0-9]{3,}|0[0-9]{3})-(0[1-9]|1[0-2])(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?',
'http://www.w3.org/2001/XMLSchema#gMonthDay' : '--(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?',
'http://www.w3.org/2001/XMLSchema#duration' : '''-?P( ( ( [0-9]+Y([0-9]+M)?([0-9]+D)?
| ([0-9]+M)([0-9]+D)?
| ([0-9]+D)
)
(T ( ([0-9]+H)([0-9]+M)?([0-9]+(\.[0-9]+)?S)?
| ([0-9]+M)([0-9]+(\.[0-9]+)?S)?
| ([0-9]+(\.[0-9]+)?S)
)
)?
)
| (T ( ([0-9]+H)([0-9]+M)?([0-9]+(\.[0-9]+)?S)?
| ([0-9]+M)([0-9]+(\.[0-9]+)?S)?
| ([0-9]+(\.[0-9]+)?S)
)
)
)''',
'http://www.w3.org/2001/XMLSchema#yearMonthDuration' : '[^DT]*',
'http://www.w3.org/2001/XMLSchema#dayTimeDuration' : '[^YM]*[DT].*',
'http://www.w3.org/2001/XMLSchema#byte' : '[\-+]?[0-9]+',
'http://www.w3.org/2001/XMLSchema#short' : '[\-+]?[0-9]+',
'http://www.w3.org/2001/XMLSchema#long' : '[\-+]?[0-9]+',
'http://www.w3.org/2001/XMLSchema#unsignedByte' : '[\-+]?[0-9]+',
'http://www.w3.org/2001/XMLSchema#unsignedShort' : '[\-+]?[0-9]+',
'http://www.w3.org/2001/XMLSchema#unsignedInt' : '[\-+]?[0-9]+',
'http://www.w3.org/2001/XMLSchema#unsignedLong' : '[\-+]?[0-9]+',
'http://www.w3.org/2001/XMLSchema#positiveInteger' : '[\-+]?[0-9]+',
'http://www.w3.org/2001/XMLSchema#nonNegativeInteger' : '[\-+]?[0-9]+',
'http://www.w3.org/2001/XMLSchema#negativeInteger' : '[\-+]?[0-9]+',
'http://www.w3.org/2001/XMLSchema#nonPositiveInteger' : '[\-+]?[0-9]+',
'http://www.w3.org/2001/XMLSchema#hexBinary' : '([0-9a-fA-F]{2})*',
'http://www.w3.org/2001/XMLSchema#base64Binary' : '((([A-Za-z0-9+/] ?){4})*(([A-Za-z0-9+/] ?){3}[A-Za-z0-9+/]|([A-Za-z0-9+/] ?){2}[AEIMQUYcgkosw048] ?=|[A-Za-z0-9+/] ?[AQgw] ?= ?=))?',
'http://www.w3.org/2001/XMLSchema#language' : '[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*',
'http://www.w3.org/2001/XMLSchema#normalizedString' : '^\S+$',
'http://www.w3.org/2001/XMLSchema#NMTOKEN' : '\c+',
'http://www.w3.org/2001/XMLSchema#Name' : '\i\c*',
'http://www.w3.org/2001/XMLSchema#NCName' : '\i\c* ∩ [\i-[:]][\c-[:]]*',
'http://www.w3.org/2001/XMLSchema#boolean' : '^(?i:true|false|0|1)$',
#ALTERNATIVE METHOD TO INDICATE DATATYPE
'xsd:integer' : '[\-+]?[0-9]+',
'xsd:double' : '(\+|-)?([0-9]+(\.[0-9]*)?|\.[0-9]+)([Ee](\+|-)?[0-9]+)? |(\+|-)?INF|NaN',
'xsd:float' : '(\+|-)?([0-9]+(\.[0-9]*)?|\.[0-9]+)([Ee](\+|-)?[0-9]+)?|(\+|-)?INF|NaN',
'xsd:any' : '.*',
'xsd:decimal' : '(\+|-)?([0-9]+(\.[0-9]*)?|\.[0-9]+)',
'xsd:time' : '(([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\.[0-9]+)?|(24:00:00(\.0+)?))(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?',
'xsd:date' : '-?([1-9][0-9]{3,}|0[0-9]{3})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?',
'xsd:dateTime' : '-?([1-9][0-9]{3,}|0[0-9]{3})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])T(([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\.[0-9]+)?|(24:00:00(\.0+)?))(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?',
'xsd:dateTimeStamp': '-?([1-9][0-9]{3,}|0[0-9]{3})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])T(([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\.[0-9]+)?|(24:00:00(\.0+)?))(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?.*(Z|(\+|-)[0-9][0-9]:[0-9][0-9])',
'xsd:string' : '.*',
'xsd:gYear' : '-?([1-9][0-9]{3,}|0[0-9]{3})(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?',
'xsd:gMonth' : '--(0[1-9]|1[0-2])(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?',
'xsd:gDay' : '---(0[1-9]|[12][0-9]|3[01])(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?',
'xsd:gYearMonth' : '-?([1-9][0-9]{3,}|0[0-9]{3})-(0[1-9]|1[0-2])(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?',
'xsd:gMonthDay' : '--(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?',
'xsd:duration' : '''-?P( ( ( [0-9]+Y([0-9]+M)?([0-9]+D)?
| ([0-9]+M)([0-9]+D)?
| ([0-9]+D)
)
(T ( ([0-9]+H)([0-9]+M)?([0-9]+(\.[0-9]+)?S)?
| ([0-9]+M)([0-9]+(\.[0-9]+)?S)?
| ([0-9]+(\.[0-9]+)?S)
)
)?
)
| (T ( ([0-9]+H)([0-9]+M)?([0-9]+(\.[0-9]+)?S)?
| ([0-9]+M)([0-9]+(\.[0-9]+)?S)?
| ([0-9]+(\.[0-9]+)?S)
)
)
)''',
'xsd:yearMonthDuration' : '[^DT]*',
'xsd:dayTimeDuration' : '[^YM]*[DT].*',
'xsd:byte' : '[\-+]?[0-9]+',
'xsd:short' : '[\-+]?[0-9]+',
'xsd:long' : '[\-+]?[0-9]+',
'xsd:unsignedByte' : '[\-+]?[0-9]+',
'xsd:unsignedShort' : '[\-+]?[0-9]+',
'xsd:unsignedInt' : '[\-+]?[0-9]+',
'xsd:unsignedLong' : '[\-+]?[0-9]+',
'xsd:positiveInteger' : '[\-+]?[0-9]+',
'xsd:nonNegativeInteger' : '[\-+]?[0-9]+',
'xsd:negativeInteger' : '[\-+]?[0-9]+',
'xsd:nonPositiveInteger' : '[\-+]?[0-9]+',
'xsd:hexBinary' : '([0-9a-fA-F]{2})*',
'xsd:base64Binary' : '((([A-Za-z0-9+/] ?){4})*(([A-Za-z0-9+/] ?){3}[A-Za-z0-9+/]|([A-Za-z0-9+/] ?){2}[AEIMQUYcgkosw048] ?=|[A-Za-z0-9+/] ?[AQgw] ?= ?=))?',
'xsd:language' : '[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*',
'xsd:normalizedString' : '^\S+$',
'xsd:NMTOKEN' : '\c+',
'xsd:Name' : '\i\c*',
'xsd:NCName' : '\i\c* ∩ [\i-[:]][\c-[:]]*',
'xsd:boolean' : '^(?i:true|false|0|1)$'
}
regex = d.get(dataType,None)
return regex
def checkString(regex,string):
match = re.fullmatch(regex,string)
if match is not None:
return True
else:
return False
def trasforrmToRegex(pattern):
pattern = '^' + pattern
pattern = pattern.replace('.',r'\\.')
pattern = pattern.replace('(',r'\\(')
pattern = pattern.replace(')',r'\\)')
pattern = pattern.replace('[',r'\\[')
pattern = pattern.replace(']',r'\\]')
pattern = pattern.replace('+',r'\\+')
pattern = pattern.replace('*',r'\\*')
pattern = pattern.replace('?',r'\\?')
pattern = pattern.replace('$',r'\\$')
return pattern
def skipCheckSSL():
try:
_create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
# Legacy Python that doesn't verify HTTPS certificates by default
pass
else:
# Handle target environment that doesn't support HTTPS verification
ssl._create_default_https_context = _create_unverified_https_context
def binarySearch(arr,l,r,x):
while l<= r:
mid = l + (r - l) // 2
if arr[mid] == x:
return mid
elif arr[mid] < x:
l = mid + 1
else:
r = mid - 1
return -1 #IF WE REACH HERE, THEN THE ELEMENT WAS NOT PRESENT
def getURINamespace(uris):
namespaces = []
for uri in uris:
r = checkURI(uri)
if r == True:
if '#' in uri:
splittedUri = uri.split('#',1)
namespace = splittedUri[0]
namespaces.append(namespace)
namespaces = list(dict.fromkeys(namespaces))
return namespaces