Best Python code snippet using autotest_python
syllabifier.py
Source:syllabifier.py
1import sys2import re3import numpy as np4dict_br_file = sys.argv[1]5dict_celex_file = sys.argv[2]6match_file = sys.argv[3]7out_file = sys.argv[4]8# match = [['@'], ['6']]9# match_br = ['6']10# match_ce = ['@']11"""12Try to match two phonemic dictionaries given a list of correspondance, apply13the syllable slicing of a dictionary to the other one14br_dict: list of "word phons"15celex_dict: list of "word [syll1][syll2] with syll1 = phon1phon216correspondance: list of phon1_br/phon2_br phon1_ce/phon2_ce17output: multiple transcriptions, single matches, unmatched words, words not18found in the celex dictionary, errors19"""20def process(br_dict, celex_dict, match_br, list_br, out):21 res = {}22 res['errors'] = ''23 res['matched'] = {}24 res['unmatched'] = ''25 res['notfound'] = ''26 n_nfound = 027 n_nmatch = 028 for br_line in br_dict:29 try:30 (br_word, br_phon) = br_line.split()31 found = False32 for celex_line in celex_dict:33 if celex_line[0] == br_word:34 found = True35 c = compare(br_phon, celex_line[1], match_br, list_br)36 if c:37 # print('found ' + br_word, [p.split(':') for p in c],38 # celex_line[1])39 addMatch(res['matched'], br_word, c)40 if found:41 if br_word not in res['matched']:42 n_nmatch += 143 res['unmatched'] += br_word + '\t' + br_phon44 for celex_line in celex_dict:45 if celex_line[0] == br_word:46 res['unmatched'] += '\t[' + ']['.join(celex_line[1]) + ']'47 res['unmatched'] += '\n'48 else:49 n_nfound += 150 res['notfound'] += br_line51 except ValueError:52 res['errors'] += br_line53 out.write('multiple matched words:\n')54 n_mult = 055 for word, segs in res['matched'].iteritems():56 aux = word + '\t'57 if len(segs) > 1:58 n_mult += 159 for seg in segs:60 # aux += '[' + ']['.join(seg.split(':')) + ']\t'61 aux += '[' + seg.replace(':', '][') + ']\t'62 out.write(aux + '\n')63 out.write('\nmatched words:\n')64 n_match = 065 for word, segs in res['matched'].iteritems():66 aux = word + '\t'67 if len(segs) == 1:68 n_match += 169 for seg in segs:70 # aux += '[' + ']['.join(seg.split(':')) + ']\t'71 aux += '[' + seg.replace(':', '][') + ']\t'72 out.write(aux + '\n')73 out.write('\nunmatched (but found) words:\n')74 out.write(res['unmatched'])75 out.write('\nnot found words:\n')76 out.write(res['notfound'])77 out.write('\nerrors\n')78 out.write(res['errors'])79 print 'multiple transcriptions: ' + str(n_mult)80 print 'number of single matches: ' + str(n_match)81 print 'number of umatched: ' + str(n_nmatch)82 print 'number of not found: ' + str(n_nfound)83def addMatch(match_list, word, matches):84 if word in match_list:85 for match in matches:86 if match not in match_list[word]:87 match_list[word] += [match]88 else:89 match_list[word] = [matches[0]]90 addMatch(match_list, word, matches)91def find_phon(phon, word):92 return phon == word[:len(phon)]93def compare(word_br, word_celex, match_br, list_br, verbose=False):94 newres = []95 # if not word_br and not word_celex:96 # # print 'ok'97 # return True98 # if not word_br or not word_celex:99 # return False100 if word_br == 'kold':101 verbose = True102 for br_phon in list_br:103 if find_phon(br_phon, word_br):104 br_subwd = word_br[len(br_phon):]105 syll = word_celex[0]106 for ce_phon in match_br[br_phon]:107 if find_phon(ce_phon, syll):108 # print ce_phon, syll109 subsyll = syll[len(ce_phon):]110 if subsyll:111 ce_subwd = [subsyll] + word_celex[1:]112 # if subsyll and word_celex[1:]:113 # print subsyll, ce_subwd114 else:115 ce_subwd = word_celex[1:]116 # print ce_subwd, br_subwd117 # if type(res) == str:118 # return word_br, br_phon + res[1]119 # else:120 # if res:121 # return word_br, br_phon122 # else:123 # return False124 if not br_subwd and not ce_subwd:125 newres.append(br_phon)126 elif not br_subwd or not ce_subwd:127 continue128 else:129 res = compare(br_subwd, ce_subwd, match_br, list_br,130 verbose)131 if subsyll:132 newres += [br_phon + br_phons133 for br_phons in res]134 else:135 newres += [br_phon + ':' + br_phons136 for br_phons in res]137 # else:138 # newres.append((br_phon, ce_phon))139 # else:140 # return False141 # if len(newres) > 1:142 # print newres143 # if verbose:144 # print newres145 return newres146def decompose_celex(celex_dict_file):147 with open(dict_celex_file) as dict_celex_f:148 res = []149 for celex_line in dict_celex_f:150 aux = celex_line.split()151 if len(aux) == 2:152 aux[1] = aux[1].replace('[', '').split(']')[:-1]153 res.append(aux)154 return res155def process_matchlist(match_file):156 match = []157 match_br = {}158 with open(match_file) as match_f:159 match_f.readline()160 for line in match_f:161 aux = line.split()[:2]162 aux[0] = aux[0].split('/')163 aux[1] = aux[1].split('/')164 match.append(aux)165 list_br = np.unique([phon for phons in match for phon in phons[1]])166 # list_ce = np.unique([phon for phons in match for phon in phons[0]])167 for phon in list_br:168 aux = []169 for l in match:170 for phon_br in l[1]:171 if phon_br == phon:172 aux += l[0]173 match_br[phon] = np.unique(aux)174 return match_br, list_br175with open(dict_br_file) as dict_br:176 (match_br, list_br) = process_matchlist(match_file)177 splitted_dict = decompose_celex(dict_celex_file)178 with open(match_file) as match_f:179 match = match_f.read()180 with open(out_file, 'w') as out:...
Dynamically_Loading_Code.py
Source:Dynamically_Loading_Code.py
1import sys, os, re2sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)) + '../lib')3from yapsy.IPlugin import IPlugin4from plugins import PluginUtil5from modules import common6from lib.pubsub import pub7import lib.plyj.parser as plyj8class DynamicallyLoadingCodePlugin(IPlugin):9 DEX_CLASS_LOADER = r'DexClassLoader'10 CLASS_LOADER = r'loadClass'11 DYNAMIC_BROADCAST_RECEIVER = r'registerReceiver'12 def __init__(self):13 self.name = 'Dynamically loading code'14 def target(self, queue):15 files = common.java_files16 global parser, tree, fileName17 parser = plyj.Parser()18 tree = ''19 res = []20 #List of Broadcast Receiver21 list_BR = []22 count = 023 for f in files:24 count += 125 pub.sendMessage('progress', bar=self.name, percent=round(count * 100 / len(files)))26 fileName = str(f)27 try:28 tree = parser.parse_file(f)29 except Exception:30 continue31 try:32 for import_decl in tree.import_declarations:33 if self.DEX_CLASS_LOADER in import_decl.name.value:34 if self.CLASS_LOADER in str(tree):35 PluginUtil.reportInfo(fileName, self.DexClassLoaderIssueDetails(fileName), res)36 # This will check if app register's a broadcast receiver dynamically37 if self.DYNAMIC_BROADCAST_RECEIVER in str(tree):38 list_BR.append(fileName)39 except Exception:40 continue41 # Arrange the Broadcast Receivers created Dynamically in column format and store it in the variable -> Broadcast_Receiver42 Broadcast_Receiver = "\n".join(list_BR)43 if list_BR:44 PluginUtil.reportWarning(fileName, self.BroadcastReceiverIssueDetails(Broadcast_Receiver), res)45 queue.put(res)46 def DexClassLoaderIssueDetails(self, fileName):47 return 'Application dynamically load an external class through DexClassLoader\n%s\n' \48 'Even though this may not be a security issue always, be careful with what you are loading. \n' \49 'https://developer.android.com/reference/dalvik/system/DexClassLoader.html \n' \50 % fileName51 def BroadcastReceiverIssueDetails(self, Broadcast_Receiver):52 return 'Application dynamically registers a broadcast receiver\n' \53 'Application that register a broadcast receiver dynamically is vulnerable to granting unrestricted access to the broadcast receiver. \n' \54 'The receiver will be called with any broadcast Intent that matches filter.\n' \55 'https://developer.android.com/reference/android/content/Context.html#registerReceiver(android.content.BroadcastReceiver, android.content.IntentFilter)\n' \56 '%s\n' \57 % Broadcast_Receiver58 def getName(self):59 return "Dynamically loading code"60 def getCategory(self):61 # Currently unused, but will be used later for clubbing issues from a specific plugin (when multiple plugins run at the same time)62 return "PLUGIN ISSUES"63 def getTarget(self):...
json_split.py
Source:json_split.py
1import json2import sys3file_path = r'X:\temp\Annotations\json\CL_HandE_1234_B004_annotations.json'4if len(sys.argv) >= 2:5 file_path = sys.argv[1]6a_file = open(file_path, "r")7json_object = json.load(a_file)8a_file.close()9list_TL, list_TR, list_BL, list_BR = [], [], [], []10center_X, center_Y = 4704, 453611for row in json_object:12 old_list = row["geometry"]["coordinates"]13 if old_list[0][0][0] < center_X and old_list[0][0][1] < center_Y:14 new_list = [[[coor[0], coor[1]] for coor in old_list[0]]]15 row["geometry"]["coordinates"] = new_list16 list_TL.append(row)17 if old_list[0][0][0] >= center_X and old_list[0][0][1] < center_Y:18 new_list = [[[coor[0] - center_X, coor[1]] for coor in old_list[0]]]19 row["geometry"]["coordinates"] = new_list20 list_TR.append(row)21 if old_list[0][0][0] < center_X and old_list[0][0][1] >= center_Y:22 new_list = [[[coor[0], coor[1] - center_Y] for coor in old_list[0]]]23 row["geometry"]["coordinates"] = new_list24 list_BL.append(row)25 if old_list[0][0][0] >= center_X and old_list[0][0][1] >= center_Y:26 new_list = [[[coor[0] - center_X, coor[1] - center_Y] for coor in old_list[0]]]27 row["geometry"]["coordinates"] = new_list28 list_BR.append(row)29assert (len(json_object) == len(list_TL) + len(list_TR) + len(list_BL) + len(list_BR))30for path, json_list in zip(["topleft", "topright", "bottomleft", "bottomright"], [list_TL, list_TR, list_BL, list_BR]):31 path_part = file_path.replace("annotations", path)32 a_file = open(path_part, "w")33 json.dump(json_list, a_file, indent=4)...
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!!