Best Python code snippet using robotframework
embtopktable.py
Source:embtopktable.py  
...89            return False90        s = t[0]91        o = t[1]92        score = t[2]93        if not s.is_variable() and not o.is_variable() and score.is_variable():94            return True95        if s.is_variable() and o.is_variable():96            return False97        if not score.is_variable():98            return False99        n_vars = 0100        unique_vars = set()101        if s.is_variable():102            unique_vars.add(s.get_value())103            n_vars += 1104        if o.is_variable():105            unique_vars.add(o.get_value())106            n_vars += 1107        if score.is_variable():108            unique_vars.add(score.get_value())109            n_vars += 1110        if len(unique_vars) != n_vars:111            return False112        return True113    def is_query_allowed(self, t: tuple) -> bool:114        return self._is_query_allowed(t)115    def get_cardinality(self, t: tuple) -> int:116        if not self._is_query_allowed(t):117            if t[0].is_variable() and t[1].is_variable() and t[2].is_variable() and t[0].get_value() != t[1].get_value() and t[1].get_value() != t[2].get_value():118                return self.n_terms * self.top_k119            else:120                print("EMBTopkTable: Tuple is not allowed!")121                raise Exception("Tuple is not allowed")122        elif not t[0].is_variable() and not t[1].is_variable():123            return 1124        return self.top_k125    def get_unique_values_in_column(self, t: tuple, column_nr) -> int:126        raise Exception("Not implemented!")127    def get_n_terms(self) -> int:128        self.n_terms + 1000 # I assume I return scores with three decimal digits of precision129    def _normalize_scores_simple(self, t : tuple, scores):130        sum = 0.0131        for s in scores:132            sum += 1 / s133        for idx, s in enumerate(scores):134            scores[idx] = 1 / (s.item()) / sum.item()135        return scores136    def _normalize_scores(self, t : tuple, scores):137        # Collect up to k max/min scores138        true_answers = self._get_true_answers(t)139        if len(true_answers) > 0:140            true_scores = self._get_answer_scores(t, true_answers)141        else:142            if t[0].is_variable():143                true_scores = self.known_min_score_s144            else:145                true_scores = self.known_min_score_o146        false_answers = self._get_false_answers(t)147        false_scores = self._get_answer_scores(t, false_answers)148        # Normalise "scores" depending on true_scores and false_scores149        best_score = torch.max(true_scores).item()150        assert(best_score <= 0)151        worst_score = torch.mean(false_scores).item()152        assert (worst_score <= 0)153        assert(best_score >= worst_score)154        clamped_scores = torch.clamp(scores, min=worst_score, max=best_score)155        scores = clamped_scores - worst_score156        range = best_score - worst_score157        prob = scores / range158        return prob159    def _get_answer_scores(self, t : tuple, a : torch.Tensor):160        if t[0].is_variable():161            # Retrieve ID of the object162            value = t[1].get_value()163            value_id = self.entities_dict[value]164            o = torch.Tensor([value_id, ]).long()165            p = torch.Tensor([self.rel_id, ]).long()166            scores = self.model.score_po(p, o, a)[0]167        #elif t[1].is_variable():168        else:169            # Retrieve ID of the subject170            value = t[0].get_value()171            value_id = self.entities_dict[value]172            s = torch.Tensor([value_id, ]).long()173            p = torch.Tensor([self.rel_id, ]).long()174            scores = self.model.score_sp(s, p, a)[0]175        #else:176        #    raise Exception("Not implemented")177        return scores178    def _get_true_answers(self, t : tuple):179        if t[0].is_variable():180            # Retrieve ID of the object181            value = t[1].get_value()182            value_id = self.entities_dict[value]183            o = torch.Tensor([value_id, ]).long().item()184            p = torch.Tensor([self.rel_id, ]).long().item()185            answers = self.known_answers_po.get([p, o])186        #elif t[1].is_variable():187        else:188            # Retrieve ID of the subject189            value = t[0].get_value()190            value_id = self.entities_dict[value]191            s = torch.Tensor([value_id, ]).long().item()192            p = torch.Tensor([self.rel_id, ]).long().item()193            answers = self.known_answers_sp.get([s, p])194        #else:195        #    raise Exception("Not implemented")196        return answers197    def _get_false_answers(self, t : tuple):198        random_entities = np.random.randint(0, self.n_terms, 10)199        return torch.from_numpy(random_entities)200    def get_iterator(self, t: tuple) -> PyIterator:201        if not self._is_query_allowed(t):202            print("EMBTopkTable: Tuple is not allowed!")203            raise Exception("Tuple is not allowed")204        answers = []205        if t[0].is_variable():206            # Retrieve ID of the object207            value = t[1].get_value()208            value_id = self.entities_dict[value]209            o = torch.Tensor([value_id, ]).long()210            p = torch.Tensor([self.rel_id, ]).long()211            scores = self.model.score_po(p, o)[0]212            s = torch.argsort(scores, descending=True)213            top_k_s = s[:self.top_k]214            top_k_scores = scores[top_k_s]215            top_k_scores = self._normalize_scores(t, top_k_scores)216            if self.score_threshold is not None:217                # Filter values with low scores218                top_k_scores = top_k_scores.double()219                top_k_scores = torch.where(top_k_scores < self.score_threshold, 0., top_k_scores)220                retained_entities = torch.nonzero(top_k_scores, as_tuple=True)221                top_k_s = top_k_s[retained_entities]222                top_k_scores = top_k_scores[retained_entities]223            txt_top_k_s = self.model.dataset.entity_strings(top_k_s)224            for idx, e in enumerate(txt_top_k_s):225                answers.append((e, value, top_k_scores[idx].item()))226        elif t[1].is_variable():227            # Retrieve ID of the subject228            value = t[0].get_value()229            value_id = self.entities_dict[value]230            s = torch.Tensor([value_id,]).long()231            p = torch.Tensor([self.rel_id, ]).long()232            scores = self.model.score_sp(s, p)[0]233            o = torch.argsort(scores, descending=True)234            top_k_o = o[:self.top_k]235            top_k_scores = scores[top_k_o]236            top_k_scores = self._normalize_scores(t, top_k_scores)237            if self.score_threshold is not None:238                # Filter values with low scores239                top_k_scores = top_k_scores.double()240                top_k_scores = torch.where(top_k_scores < self.score_threshold, 0., top_k_scores)...get_instances.py
Source:get_instances.py  
1import itertools2from geosolver.diagram.computational_geometry import polygon_is_convex, angle_in_radian3from geosolver.diagram.states import GraphParse4from geosolver.ontology.instantiator_definitions import instantiators5from geosolver.ontology.ontology_definitions import FormulaNode, signatures6import numpy as np7from geosolver.ontology.ontology_semantics import MeasureOf8__author__ = 'minjoon'9def get_instances(graph_parse, instance_type_name, is_variable, *args):10    assert instance_type_name in instantiators11    if instance_type_name in ["triangle", "quad", 'hexagon', 'polygon']:12        return _get_polygons(graph_parse, instance_type_name, is_variable, *args)13    else:14        return eval("_get_%ss(graph_parse, is_variable, *args)" % instance_type_name)15def get_all_instances(graph_parse, instance_type_name, is_variable=False):16    if instance_type_name == 'polygon':17        triangles = _get_all_polygons(graph_parse, 'triangle', 3, is_variable)18        quads = _get_all_polygons(graph_parse, 'quad', 4, is_variable)19        hexagons = _get_all_polygons(graph_parse, 'hexagon', 6, is_variable)20        polygons = dict(triangles.items() + quads.items() + hexagons.items())21        return polygons22    elif instance_type_name in ["triangle", "quad", "hexagon"]:23        if instance_type_name == 'triangle': n = 324        elif instance_type_name == 'quad': n = 425        elif instance_type_name == 'hexagon': n = 626        return _get_all_polygons(graph_parse, instance_type_name, n, is_variable)27    else:28        return eval("_get_all_%ss(graph_parse, is_variable)" % instance_type_name)29def _get_points(graph_parse, is_variable, key):30    if key in graph_parse.intersection_points:31        if is_variable:32            return {key: graph_parse.core_parse.point_variables[key]}33        else:34            return {key: graph_parse.intersection_points[key]}35    else:36        return {}37def _get_all_points(graph_parse, is_variable):38    items = []39    for key in graph_parse.intersection_points.keys():40        items.extend(_get_points(graph_parse, is_variable, key).iteritems())41    return dict(items)42def _get_lines(graph_parse, is_variable, a_key, b_key):43    assert isinstance(graph_parse, GraphParse)44    if graph_parse.line_graph.has_edge(a_key, b_key):45        if is_variable:46            line = graph_parse.line_graph[a_key][b_key]['variable']47        else:48            line = graph_parse.line_graph[a_key][b_key]['instance']49        return {(a_key, b_key): line}50    else:51        return {}52def _get_all_lines(graph_parse, is_variable):53    assert isinstance(graph_parse, GraphParse)54    items = []55    for a_key, b_key in graph_parse.line_graph.edges():56        items.extend(_get_lines(graph_parse, is_variable, a_key, b_key).iteritems())57    return dict(items)58def _get_circles(graph_parse, is_variable, center_key):59    assert isinstance(graph_parse, GraphParse)60    if center_key in graph_parse.circle_dict:61        circles = {}62        for radius_key, d in graph_parse.circle_dict[center_key].iteritems():63            if is_variable:64                circle = d['variable']65            else:66                circle = d['instance']67            circles[(center_key, radius_key)] = circle68        return circles69    else:70        return {}71def _get_all_circles(graph_parse, is_variable):72    assert isinstance(graph_parse, GraphParse)73    items = []74    for center_key in graph_parse.circle_dict:75        items.extend(_get_circles(graph_parse, is_variable, center_key).iteritems())76    return dict(items)77def _get_arcs(graph_parse, is_variable, a_key, b_key):78    assert isinstance(graph_parse, GraphParse)79    arcs = {}80    for circle_key in _get_all_circles(graph_parse, is_variable):81        if graph_parse.arc_graphs[circle_key].has_edge(a_key, b_key):82            test_arc = graph_parse.arc_graphs[circle_key][a_key][b_key]['instance']83            circle, a, b = test_arc84            test_angle = instantiators['angle'](a, circle.center, b)85            if angle_in_radian(test_angle) > np.pi:86                a_key, b_key = b_key, a_key87            if is_variable:88                arc = graph_parse.arc_graphs[circle_key][a_key][b_key]['variable']89            else:90                arc = graph_parse.arc_graphs[circle_key][a_key][b_key]['instance']91            arc_key = (circle_key, a_key, b_key)92            arcs[arc_key] = arc93    return arcs94def _get_all_arcs(graph_parse, is_variable):95    assert isinstance(graph_parse, GraphParse)96    items = []97    for a_key, b_key in itertools.combinations(graph_parse.intersection_points, 2):98        items.extend(_get_arcs(graph_parse, is_variable, a_key, b_key).iteritems())99    return dict(items)100def _get_polygons(graph_parse, name, is_variable, *args):101    # TODO : include ignore_trivial parameter. This ignores area-0 polygons.102    assert isinstance(graph_parse, GraphParse)103    line_graph = graph_parse.line_graph104    if all(line_graph.has_edge(args[idx-1], arg) for idx, arg in enumerate(args)):105        convex = polygon_is_convex(tuple(graph_parse.intersection_points[key] for key in args))106        if is_variable:107            points = list(graph_parse.core_parse.point_variables[key] for key in args)108        else:109            points = list(graph_parse.intersection_points[key] for key in args)110        if not convex:111            points.reverse()112        polygon = FormulaNode(signatures[name.capitalize()], points)113        polygon_key = tuple(args)114        return {polygon_key: polygon}115    else:116        return {}117def _get_all_polygons(graph_parse, name, n, is_variable):118    polygons = {}119    frozensets = set()120    line_graph = graph_parse.line_graph121    for keys in itertools.permutations(graph_parse.intersection_points, n):122        if frozenset(keys) in frozensets:123            continue124        if not all(line_graph.has_edge(keys[idx-1], key) for idx, key in enumerate(keys)):125            continue126        angles = []127        for idx, key in enumerate(keys):128            angles.extend(_get_angles(graph_parse, False, keys[idx-2], keys[idx-1], key).values())129        if len(angles) < n:130            continue131        convex = polygon_is_convex(tuple(graph_parse.intersection_points[key] for key in keys))132        if is_variable:133            points = list(graph_parse.core_parse.point_variables[key] for key in keys)134        else:135            points = list(graph_parse.intersection_points[key] for key in keys)136        if not convex:137            points.reverse()138        # polygon = instantiators[name](*points)139        polygon = FormulaNode(signatures[name.capitalize()], points)140        polygon_key = tuple(keys)141        polygons[polygon_key] = polygon142        frozensets.add(frozenset(keys))143    return polygons144def _get_angles(graph_parse, is_variable, a_key, b_key, c_key, ignore_trivial=True):145    assert isinstance(graph_parse, GraphParse)146    line_graph = graph_parse.line_graph147    if line_graph.has_edge(a_key, b_key) and line_graph.has_edge(b_key, c_key):148        if ignore_trivial:149            # line_a = line_graph[b_key][a_key]['instance']150            a_points = line_graph[b_key][a_key]['points']151            # line_c = line_graph[b_key][c_key]['instance']152            c_points = line_graph[b_key][c_key]['points']153            if c_key in a_points or a_key in c_points:154                return {}155            if line_graph.has_edge(a_key, c_key):156                """157                Removes flat angle (180 degrees)158                """159                b_points = line_graph[a_key][c_key]['points']160                if b_key in b_points:161                    return {}162        if is_variable:163            points = graph_parse.core_parse.point_variables164            a, b, c = points[a_key], points[b_key], points[c_key]165            angle = FormulaNode(signatures['Angle'], [a, b, c])166        else:167            points = graph_parse.intersection_points168            a, b, c = points[a_key], points[b_key], points[c_key]169            angle = instantiators['angle'](a, b, c)170        angle_key = (a_key, b_key, c_key)171        return {angle_key: angle}172    else:173        return {}174def _get_all_angles(graph_parse, is_variable, ignore_trivial=True):175    """176    If ignore_trival is set to true, then 0 degree / 360 degree angles are not considered.177    :param graph_parse:178    :param ignore_trival:179    :return:180    """181    assert isinstance(graph_parse, GraphParse)182    items = []183    for a_key, b_key, c_key in itertools.permutations(graph_parse.intersection_points, 3):184        items.extend(_get_angles(graph_parse, is_variable, a_key, b_key, c_key, ignore_trivial=ignore_trivial).iteritems())...Мелентьев Петр Алексеевич KNN.py
Source:Мелентьев Петр Алексеевич KNN.py  
1#!/usr/bin/env python2# coding: utf-83# In[1]:4import pandas as pd5import numpy as np6import math7from matplotlib import pyplot as plt8from scipy.spatial import distance9filename = "datasets/heart.csv"10CLASSES = 511# In[2]:12def minmax(dataset):13    minmax = list()14    for i in range(len(dataset[0])):15        if i == len(dataset[0]) - 1:16            continue17        value_min = dataset[:, i].min()18        value_max = dataset[:, i].max()19        minmax.append([value_min, value_max])20    return minmax21# In[3]:22def normalize(_dataset, min_max):23    for row in _dataset:24        for i in range(len(row)):25            if i == len(row) - 1:  # exclude labels26                continue27            dif = min_max[i][1] - min_max[i][0]28            row[i] = ((row[i] - min_max[i][0]) / dif) if dif != 0 else 029    return _dataset30# In[4]:31def draw_plot(dataset, feature1N, feature2N, target):32    iris_type_to_color = {33        1.0 : "g",34        2.0 : "b",35        3.0 : "y",36        4.0 : "m",37        5.0 : "c"38    }39    colored_irises = list(map(lambda x: iris_type_to_color[x], dataset[:, -1]))40    colored_irises.append("r")41    x = list(dataset[:, feature1N])42    y = list(dataset[:, feature2N])43    x.append(target[feature1N])44    y.append(target[feature2N])45    plt.scatter(x, y, c=colored_irises)46    plt.show()47# In[5]:48dataset = pd.read_csv(filename, dtype=np.float64)49# In[6]:50pd.DataFrame(dataset.values)51# In[7]:52min_max = minmax(dataset.values)53normalized_dataset_values = normalize(dataset.values.copy(), min_max)54pd.DataFrame(normalized_dataset_values)55# In[8]:56def kNN(dataset, distf, target, k):57    distances = list()58    for row in dataset:59        dist = distf(target, row[:-1])60        distances.append((row, dist))61    distances.sort(key=lambda tup: tup[1])62    63#     neighbors = list()64#     for i in range(k):65#         neighbors.append(distances[i][0])66    return distances[-1][1]67# In[9]:68def NWreg(dataset, x, dist, kernel, H, variable=False, onehot=False, lables=None):69    up = 070    gr = 071    if variable:72        H = kNN(dataset, dist, x, H)73    for idx, row in enumerate(dataset):74        weight = kernel(dist(row[:-1], x) / H)75        up += row[-1] * weight76        if onehot and lables is not None:77            up += lables[idx] * weight78        gr += weight79    return up / gr if gr != 0 else 080# In[10]:81def F_macro(CM):82    TP = []83    FP = []84    FN = []85    F_micro = 086    F_macro = 087    All = sum(list(sum(e) for e in zip(*CM)))88    89    def Prec(c):90        _gr = TP[c] + FP[c]91        return TP[c] / _gr if _gr != 0 else 092    def Recall(c):93        _gr = TP[c] + FN[c]94        return TP[c] / _gr if _gr != 0 else 095    def F_score(c, b=1):96        _prec = Prec(c)97        _recall = Recall(c)98        if _prec != 0 and _recall != 0:99            return (1 + pow(b, 2)) * _prec * _recall / (pow(b, 2) * _prec + _recall)100        else:101            return 0102    def PrecW():103        _sum = 0104        for i in range(CLASSES):105            P = sum(list(e[i] for e in CM))106            _sum += CM[i][i] * sum(CM[i]) / P if P != 0 else 0107        return _sum / All108    def RecallW():109        return sum(CM[i][i] for i in range(CLASSES)) / All110    for i in range(CLASSES):111        tp = CM[i][i]112        TP.append(tp)113        FN.append(sum(CM[i]) - tp)114        FP.append(sum(list(e[i] for e in CM)) - tp)115        F_micro += (sum(CM[i]) * F_score(i)) / All116    return 2 * PrecW() * RecallW() / (PrecW() + RecallW())117# In[11]:118euclidean = distance.euclidean119manhattan = distance.cityblock120chebyshev = distance.chebyshev121distances = [euclidean, manhattan, chebyshev]122# In[12]:123def epanechnikov(u):124    return 3 * (1 - pow(u, 2)) / 4 if u < 1 else 0125def uniform(u):126    return 0.5 if u < 1 else 0127def triangular(u):128    return 1 - abs(u) if u < 1 else 0129def quartic(u):130    return 15*pow(1-pow(u,2), 2) / 16 if u < 1 else 0131def triweight(u):132    return 35*pow(1-pow(u,2), 3) / 32 if u < 1 else 0133def tricube(u):134    return 70*pow(1-pow(abs(u),3), 3) / 81 if u < 1 else 0135def gaussian(u):136    return math.exp(-pow(u,2) / 2) / math.sqrt(2*math.pi)137def cosine(u):138    return (math.pi * math.cos((math.pi * u) / 2)) / 4 if u < 1 else 0139def logistic(u):140    return 1 / (math.exp(u) + 2 + math.exp(-u))141def sigmoid(u):142    return 2 / (math.pi * (math.exp(u) + math.exp(-u)))143kernels = [epanechnikov, uniform, triangular, quartic, triweight, tricube, gaussian, cosine, logistic, sigmoid]144# In[25]:145def regression(dataset):146    maxfscore = 0147    best = []148    bestCM = np.zeros((CLASSES, CLASSES))149    for kernel in kernels:150        for distance in distances:151            for is_variable in [False, True]:152                if is_variable:153                    windows = [x for x in range(2, 25)]154                else:155                    windows = [x * 0.1 for x in range(40, 250)]156                for window in windows:157                    CM = np.zeros((CLASSES, CLASSES))158                    for i in range(len(dataset.values)):159                        curr_dataset = [row for idx, row in enumerate(dataset.values) if idx != i]160                        res = NWreg(curr_dataset, dataset.values[i][:-1],161                                    distance, kernel, window, is_variable)162                        predicted = round(res) if res >= 0.5 else 1163                        expected = round(dataset.values[i][-1])164                        CM[predicted-1][expected-1] += 1165                    fscore = F_macro(CM)166                    if fscore > maxfscore:167                        maxfscore = fscore168                        best = [kernel, distance, window, is_variable]169                        bestCM = CM170    print(str(best))171    print(pd.DataFrame(bestCM))172    print("F score: " + maxfscore.__str__())173    return best, bestCM, maxfscore174# In[26]:175best, cm, fsc = regression(dataset)176# In[13]:177onehot = pd.get_dummies(normalized_dataset_values[:,-1])178onehot179# In[18]:180def regression(dataset, onehot): # for onehot181    maxfscore = 0182    best = []183    bestCM = np.zeros((CLASSES, CLASSES))184    for kernel in kernels:185        for distance in distances:186            for is_variable in [False, True]:187                if is_variable:188                    windows = [x for x in range(2, 25)]189                else:190                    windows = [x * 0.1 for x in range(40, 250)]191                for window in windows:192                    CM = np.zeros((CLASSES, CLASSES))193                    for i in range(len(dataset.values)):194                        curr_dataset = [row for idx, row in enumerate(dataset.values) if idx != i]195                        res = NWreg(curr_dataset, dataset.values[i][:-1],196                                    distance, kernel, window, variable=is_variable, onehot=True, lables=onehot)197                        if not isinstance(res, int):198                            predicted = np.where(res == max(res))[0][0]199                            #print(kernel.__str__(), str(distance), str(window), str(is_variable), str(predicted))200                        else:201                            predicted = 1202                        expected = round(dataset.values[i][-1])203                        CM[predicted][expected-1] += 1204                    fscore = F_macro(CM)205                    if fscore > maxfscore:206                        maxfscore = fscore207                        best = [kernel, distance, window, is_variable]208                        bestCM = CM209    print(str(best))210    print(pd.DataFrame(bestCM))211    print("F score: " + maxfscore.__str__())212    return best, bestCM, maxfscore213# In[19]:214best1h, cm1h, fsc1h = regression(dataset, onehot.values)215# In[21]:216def plot1(dataset):217    fscs = []218    winsize = []219    windows = [x * 0.1 for x in range(20, 250)]220    for window in windows:221        CM = np.zeros((CLASSES, CLASSES))222        for i in range(len(dataset.values)):223            curr_dataset = [row for idx, row in enumerate(dataset.values) if idx != i]224            res = NWreg(curr_dataset, dataset.values[i][:-1], manhattan, logistic, window)225            predicted = round(res) if res >= 0.5 else 1226            expected = round(dataset.values[i][-1])227            CM[predicted-1][expected-1] += 1228        fscs.append(F_macro(CM))229        winsize.append(window)230    plt.plot(winsize, fscs)231plot1(dataset)...test_regex.py
Source:test_regex.py  
1from functionrefactor.parser import Regex2from tests.common_functions import *3def test_comment_regex():4    r = Regex()5    assert r.comment_single_line.match("//comment")6    assert r.comment_single_line.match("    //comment something")7    assert r.comment_multiline.match("    /*comment something*/")8    assert r.comment_multiline.match("    /*comment \n something*/")9    assert r.comment_multiline_begin.match(10        "    /*comment \n something \n \n \n \n")11    assert r.comment_multiline_begin.match("    /*c++")12    assert r.comment_multiline_end.match("comment */")13    assert r.comment_multiline_end.match("comment \n something \n */   ")14def test_preprocessor_regex():15    r = Regex()16    assert r.preprocessor_c.match("#define")17    assert r.preprocessor_c.match("#define MACRO_ SOMETHING(){} \ ")18    assert r.includes.match("#include <string>")19    assert r.includes.match("#include \"_header\" ")20    assert r.generic_preprocessor.match("#ifdef SOMETHING")21    assert r.generic_preprocessor.match("#endif //SOMETHING ELSE")22    assert r.line_continuation.match(r"#define MACRO \ ")23    assert r.line_continuation.match(r"return CAPSLOCKMANDATORY; \ ")24def test_class_namespace_regex():25    r = Regex()26    assert r.namespace.match("namespace std \n {")27    assert r.namespace.match("      namespace SuperNamespace{")28    assert r.class_.match("class Nutella{")29    assert not r.class_.match("      class;")30    assert r.class_.match("class Porridge{")31    assert r.struct_.match("struct{")32    assert r.struct_.match("      struct \n \n Cereal{")33    assert r.union_.match(' union Oats{ }')34    assert r.union_.match(' union Variant{ ')35def test_template_arg_packing():36    r = Regex()37    assert r.template.match('  template  typename<>')  # look for template start38    assert r.template.match('  template')  # look for template start39    assert r.template_args.search("template <typename T>")40    assert r.template_args.search(41        "template <class T0, class T1, \n int X = 10 >")42    assert r.template_args.search(43        "template <class T0, class T1, \n int X = 10 > /* */")44def test_text_quotes():45    r = Regex()46    assert r.string_block.search(r" \" something ))) \" ")47    assert r.char_block.search(r" \' c \' ")48def test_variable_and_function_regex():49    r = Regex()50    assert r.is_variable.match("int var;")51    assert r.is_variable.match("auto i{0};")52    assert r.is_variable.match("int i =0;")53    assert r.is_variable.match("auto i{0};")54    assert r.is_variable.match("std::vector<std::string> vec{};")55    assert r.is_variable.match(56        r"std::vector<std::string> vec={\"a\",\"b\",\"c\"}; //abc")57    assert r.is_variable.match(58        r"std::vector<std::string> vec=(\"a\",\"b\",\"c\"); //abc")59    assert r.is_variable.match(r"std::vector<std::string> vec=(\n); //abc")60    assert r.is_variable.match("std::vector<std::string> vec\n{\n}\n;")61    assert r.is_variable.match(62        "constexpr f = [&](auto& a, auto& b)->{return a+b;}")63    assert r.is_variable.match(64        "constexpr f = [&](auto& a, auto& b)->{\n return a+b; \n}")65    assert not r.is_variable.match("int main();")66    assert not r.is_variable.match("int main() { }")67    assert not r.is_variable.match(68        "virtual std::string get_tag(const std::string& key)=0; ")69    # assert r.is_variable.match(r"int i(0); //abc") note this is not a valid variable declaration 70    # in a C++ header file, so no test for this is needed71    full_regex_match("auto i =0;", r.variable_capture)72    full_regex_match("auto i{0};", r.variable_capture)73    full_regex_match("std::vector<std::string> vec{};", r.variable_capture)74    full_regex_match(r"std::vector<std::string> vec={\"a\",\"b\",\"c\"};",75                     r.variable_capture)76    full_regex_match(r"std::vector<std::string> vec=(\"a\",\"b\",\"c\");",77                     r.variable_capture)78    full_regex_match(r"std::vector<std::string> vec=(\n);", r.variable_capture)79    full_regex_match("std::vector<std::string> vec\n{\n}\n;",80                     r.variable_capture)81    #lambda test82    full_regex_match("constexpr f = [&](auto& a, auto& b)->{return a+b;};",83                     r.variable_capture)84    full_regex_match(85        "constexpr f = [&](auto& a, auto& b)->{\n return a+b; \n};",86        r.variable_capture)87    #function match88    assert r.is_function.match("   int main();")89    assert r.is_function.match("int main() { }")90    assert r.is_function.match("void do_things(const i* const ptr) {}")91    assert r.is_function.match(92        "             virtual std::string get_tag(const std::string& key)=0; ")93    assert not r.is_function.match("auto i =0;")94    assert not r.is_function.match("auto i{0};")95    assert not r.is_function.match("std::vector<std::string> vec{};")96    assert not r.is_function.match(97        r"std::vector<std::string> vec={\"a\",\"b\",\"c\"}; //abc")98    assert not r.is_function.match(99        r"std::vector<std::string> vec=(\"a\",\"b\",\"c\"); //abc")100    assert not r.is_function.match(r"std::vector<std::string> vec=(\n); //abc")101    assert not r.is_function.match("std::vector<std::string> vec\n{\n}\n;")102    full_regex_match("int main();", r.function_capture)103    full_regex_match("int main(){}", r.function_capture)104    full_regex_match("long long get_key(){\n return 42; \n}",105                     r.function_capture)106    full_regex_match("long long get_key(int k){\n return k+42; \n}",107                     r.function_capture)108    full_regex_match("long long \n get_key() \n {\n return 42; \n}",109                     r.function_capture)110    #function parameters extraction111    assert r.function_parameters.search(112        "int main(const std::string& a, const std::vector<int>& vec);")113    assert r.function_parameters.search("int main();")114    assert r.function_parameters.search(115        "int main(const std::string& a, const std::vector<int>& vec = { 1, 2, 3, 4} );"116    )117    #verification that the full parameter list is extracted in all cases118    full_regex_search(119        "int main(const std::string& a, const std::vector<int>& vec);",120        r.function_parameters,121        "(const std::string& a, const std::vector<int>& vec)")122    full_regex_search(123        "int main(const std::string& a, const std::vector<int>& vec = {1,2,3,4});",124        r.function_parameters,125        "(const std::string& a, const std::vector<int>& vec = {1,2,3,4})")126    full_regex_search(127        "int main(const std::string& a, \n const std::vector<int>& vec \n = {1,2,3,4});",128        r.function_parameters,...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!!
