Best Python code snippet using fMBT_python
graph.py
Source:graph.py  
...144                discovered.append(c)145            # se actualiza u = c146            u = c147        return tree148    def addDistances(self, rangeL=2, rangeR=50):149        """150        rangeL: left limit (int). Default 2.151        rangeR: right limit (int). Default 50.152        return distances (list)153        Create a list of random integer numbers for each edge of random graph.154        """155        n_edges = len(self.edges)156        distances = [random.randint(rangeL, rangeR) for _ in range(n_edges)]157        return distances158    def createAdjMat(self):159        """160        return m (numpy 2D-array)161        Creates the adjacent matrix of random graph"""162        distances = self.addDistances()163        n_dis = len(distances)164        n_nodes = len(self.nodes)165        edges = self.edges166        m = np.ones((n_nodes, n_nodes))*np.inf167        c = 0168        for e in edges:169            i = int(e.split("->")[0])170            j = int(e.split("->")[1])171            m[i, j] = distances[c]172            m[j, i] = distances[c]173            c += 1174        for i in range(m.shape[0]):175            for j in range(m.shape[1]):176                if i == j:177                    m[i, j] = 0178        return m179    def Dijkstra(self, s):180        """181        s: source node (int)182        return: dg (Graph)183        Returns Dijkstra tree from random graph"""184        dg = Graph()  # Dijkstra graph185        dg.typee = 9  # id of graph186        mat = self.createAdjMat()  # adjacent matrix mat187        INF = np.inf  # varible with infinite value to represent nodes no neighbors188        distancias = [INF]*mat.shape[0]  # vector de distancias minimas189        visto = [False]*mat.shape[0]  # vector de nodos visitados190        padre = [-1]*mat.shape[0]  # nodos padres191        caminos = [()]*mat.shape[0]  # caminos192        distancias[s] = mat[s][s]  # distance of s to s is 0.193        while sum(visto) < len(visto):194            dismin = INF  # dismin195            v_min = 0  # nodo con distancia minima196            for i in range(len(visto)):197                # se obtiene el nodo de distancia minima198                if visto[i] == False and distancias[i] < dismin:199                    dismin = distancias[i]200                    v_min = i  # nodo de distancia minima201            visto[v_min] = True  # se marca como visto el nodo202            for i in range(len(visto)):  # si L(y) > L(x)+w(x,y)203                if not visto[i] and mat[v_min][i] != 0 and distancias[i] > distancias[v_min] + mat[v_min][i]:204                    # se actualiza nueva distancia mÃnima205                    distancias[i] = distancias[v_min] + mat[v_min][i]206                    padre[i] = v_min  # se obtiene el nodo padre del nodo i207        # Para obtener los caminos208        for i in range(len(padre)):209            nodo = i  # nodo final210            c = []211            while nodo != -1:  # hasta que se llegue al nodo inicio212                c.append(nodo)  # se guarda el nodo213                nodo = padre[nodo]  # y se mueve al nodo predecesor214            caminos[i] = c[::-1]215        # Agregar edges al grafo dg (Graph)216        for camino in caminos:217            if len(camino) > 1:218                p = 0219                while p < len(camino)-1:220                    dg.addEdge(camino[p], camino[p+1],221                               f"{camino[p]}->{camino[p+1]}")222                    p += 1223        # Se crea lista orden para pasar las distancias de cada nodo a s en gephi224        orden = []225        for camino in caminos:226            for r in camino:227                if r not in orden:228                    orden.append(r)229        # Se agregan las distancias a dg (Graph)230        for r in orden:231            dg.ds.append(distancias[r])232        return dg233    def KruskalD(self):234        kg = Graph()  # Kruskal Graph235        kg.typee = 10  # id of graph236        distances = self.addDistances()237        vertex = list(self.edges.keys())238        sorted_vertex = []239        sorted_distances = []240        # vertex and distances ordered ascendently241        for _ in range(len(distances)):242            idx_min_distance = np.argmin(distances)243            sorted_vertex.append(vertex[idx_min_distance])244            sorted_distances.append(distances[idx_min_distance])245            vertex.pop(idx_min_distance)246            distances.pop(idx_min_distance)247        # Connected component248        connected_components = []249        for i in range(len(self.nodes)):250            temp = [False]*len(self.nodes)251            temp[i] = True252            connected_components.append(temp)253        # iteratee over all graph's vertex and check if their nodes don't belong254        # to the same subset to create edge in kruskal tree255        for i in range(len(sorted_vertex)):256            u = int(sorted_vertex[i].split('->')[0])257            v = int(sorted_vertex[i].split('->')[-1])258            # if u and v aren't in the same subset259            if connected_components[u] != connected_components[v]:260                kg.addEdge(u, v, f"{u}->{v}")261                for x in range(len(connected_components[u])):262                    if connected_components[u][x]:263                        for y in range(len(connected_components[v])):264                            if connected_components[v][y]:265                                connected_components[x][y] = True266                                connected_components[y][x] = True267                kg.mst += sorted_distances[i]268        return kg269    def KruskalI(self):270        kg = Graph()  # Kruskal Graph271        kg.typee = 11  # id of graph272        distances = self.addDistances()273        vertex = list(self.edges.keys())274        sorted_vertex = []275        sorted_distances = []276        # vertex and distances ordered ascendently277        for _ in range(len(distances)):278            idx_min_distance = np.argmin(distances)279            sorted_vertex.append(vertex[idx_min_distance])280            sorted_distances.append(distances[idx_min_distance])281            vertex.pop(idx_min_distance)282            distances.pop(idx_min_distance)283        # Connected component284        connected_components = []285        for i in range(len(self.nodes)):286            temp = [False]*len(self.nodes)...Preprocessing.py
Source:Preprocessing.py  
...28    'findRoute(Route) :- retractall(added(_)), retractall(edge(_,_)), retractall(visited(_)), retractall(route(_)), '29    'sortPools(Pools), first(Pools,Root), assertz(added(Root)), delete(Pools,Root,RootlessPools), leastDistant(Root, '30    'RootlessPools, Min), assertz(edge(Root,Min)), assertz(added(Min)), delete(RootlessPools,Min,LessPools), '31    'buildTree(LessPools), assertz(visited(Root)), assertz(route([])), preorder(Root), route(Partial), push(Root,'32    'Partial,Partial2), first(Root,Name), addDistances([[Name,0]],Partial2,_,0,Route). %Retracts and sets all dynamic '33    'predicates, sorts the pool list, sets the root node of the tree, adds an edge to the closest node in the pool '34    'list (excluding root), builds the tree, traverses the tree in preorder and sums the distance traveled at each '35    'node. Appends the distances to the corresponding node and returns this list (Route).\n\n' +36    'writeToFile([],_).\n'37    'writeToFile([H|T],Out) :- first(H,Name), last(H,Distance), write(Out,Name), write(Out," "), write(Out,Distance), '38    'nl(Out), writeToFile(T,Out). %Opens file File in append mode with output stream Out and takes the Name and '39    'Distance of the first element in the route list and writes it to the file. Repeats the process recursively for '40    'each element in the list\n\n' +41    'sortPools(Sorted) :- pools(List), predsort(compareLongitude,List,Sorted). %Sorts the pools list using the '42    'predicate compareLatitude\n\n' +43    'compareLongitude(X,[_,Longitude1,_],[_,Longitude2,_]) :- compare(X,Longitude1,Longitude2). %Compares latitudes '44    'of two pools and returns the symbol equalling the result of the comparison (<, ==, >)\n\n' +45    'first([H|_], H). %Returns the head of a list\n\n'46    'leastDistant(Node,List,Min) :- predsort(compareDistance(Node),List,Sorted), first(Sorted,Min). %Finds the least '47    'distant node (Min) in the List from Node by sorting the list using predicate compareDistance and taking the '48    'first element of the returned sorted list\n\n' +49    'compareDistance(Node,X,Node1,Node2) :- distance(Node,Node1,Distance1), distance(Node,Node2,Distance2), '50    'compare(X,Distance1,Distance2). %Compares the distance between Node and Node1 with the distance between Node and '51    'Node2 and returns the symbol equalling the result of the comparison (<, ==, >)\n\n' +52    'distance([_,Longitude1,Latitude1],[_,Longitude2,Latitude2],Distance) :- toRadians(Latitude1,Lat1), toRadians('53    'Latitude2,Lat2), toRadians(Longitude1,Lon1), toRadians(Longitude2,Lon2), Distance is 6371*2*asin(sqrt(((sin(('54    'Lat1-Lat2)/2))^2)+cos(Lat1)*cos(Lat2)*((sin((Lon1-Lon2)/2))^2))). %Calculates the distance in kilometers between '55    'two geopgraphical coordinates\n\n' +56    'toRadians(Degrees, Degrees*(pi/180)). %Converts Degrees to Radians\n\n' +57    'buildTree([]).\n' +58    'buildTree([H|T]) :- setof(Nodes,added(Nodes),Tree), leastDistant(H,Tree,Min), assertz(edge(Min,H)), '59    'assertz(added(H)), buildTree(T). %Builds a tree by checking the nodes that are currently in the tree (added(_)), '60    'finding the node in the tree that is least distant (Min) from the current node (H) and creates an edge between '61    'the two. Repeats the process recursively until all nodes are added (list is empty)\n\n' +62    'preorder(_) :- setof(Nodes,added(Nodes),Added), setof(Nodes,visited(Nodes),Visited), Added == Visited.\n' +63    'preorder(Node) :- edge(Node,Child), assertz(visited(Child)), route(Partial), append(Partial,[Child],Route), '64    'retractall(route(_)), assertz(route(Route)), preorder(Child). %For each edge between Node and Child, '65    'visit Child, take the name, append the element to the cumulative route and update the cumulative route. Repeat '66    'the process recursively until all nodes have been visited\n\n' +67    'push(Element,List,[Element|List]). %Appends an Element to the front of the List\n\n' +68    'addDistances(Route,[_|[]],_,_,Route).\n' +69    'addDistances(Partial,[H|T],Acc,Sum,Route) :- first(T,B), distance(H,B,Distance), Sum1 is Sum+Distance, first(B,'70    'Name), append(Partial,[[Name,Sum1]],Acc), addDistances(Acc,T,_,Sum1,Route). %Calculates the distance between the '71    'next head and the current head and appends the distance to the current head. Repeat the process recursively '72    'until the next head is empty '73)74prolog_file.close()...uq_feed_helper.py
Source:uq_feed_helper.py  
...24                res.append(each)25        else:26            if lot == lotInfo:27                res.append(each)28    parkinfo = addDistances(res, CONFIG, location)29    return parkinfo30def getResponse(PARKINGLOTINFO, lot, location, CONFIG, userType="S"):31    parkinginfo = parseFeed(PARKINGLOTINFO)32    res = getUserSpecificResponse(parkinginfo, userType, lot, CONFIG, location)33    return res34def addDistances(parkinginfo, CONFIG, location):35    allGeo = []36    for each in parkinginfo:37        allGeo.append(each["geo"])38    geos = "|".join(allGeo)39    distanceinfo = getDistance(location, geos, CONFIG)40    distanceinfo = distanceinfo["rows"][0]["elements"]41    for ind, item in enumerate(parkinginfo):42        item["distance"] = distanceinfo[ind]["distance"]["value"]43        item["duration"] = distanceinfo[ind]["duration"]["text"]44    return parkinginfo45def getUserSpecificResponse(parkinginfo, userType, lot, CONFIG, location):46    res = []47    if lot != "":48        temp = []49        for each in parkinginfo:50            lotParts = []51            realLot = each["lot"]52            if " " in realLot:53                lotParts = realLot.split(" ")54            else:55                lotParts.append(realLot)56            if lot in lotParts:57                temp.append(each)58            for t in temp:59                if userType in t["type"]:60                    res.append(t)61        parkinfo = addDistances(res, CONFIG, location)62        if len(parkinfo) > 0:63            parkinfo.sort(key=lambda x: x["distance"])64        else:65            parkinfo = []66        return parkinfo67    else:68        for each in parkinginfo:69            if userType in each["type"]:70                res.append(each)71        parkinfo = addDistances(res, CONFIG, location)72        if len(parkinfo) > 0:73            parkinfo.sort(key=lambda x: x["distance"])74        else:75            return []76        for park in parkinfo:77            if park["distance"] > 1000:78                park["distance"] = "{:.1f}".format(float(park["distance"] / 1000)) + " kilometers"79            else:80                park["distance"] = "{} meters".format(park["distance"])81        return parkinfo82def getDistance(my, park, CONFIG):83    response = requests.get("{}?origins={}&destinations={}&key={}".format(CONFIG["google_map_url"], my, park, CONFIG["google_map_key"]))84    if response.status_code == 200:85        content = json.loads(response.content)...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!!
