Best Python code snippet using locust
production-dicts.py
Source:production-dicts.py  
...58def simple_transformer(sphere, index, row, lst, field, fields):59    idx = _name_ixd(field["name"], fields)60    input = strutils.build_input(row[idx])61    a = utils.to_action(index, "dict", input, input, row[idx].strip(),62                        {"name": strutils.to_name(row[idx])})63    lst[strutils.to_name(row[idx])] = a64def default_conv(val):65    return strutils.to_name(val)66def float_floor_conv(val):67    if not val:68        return 069    float_val = float(val)70    return math.floor(float_val)71def int_conv(val):72    if not val:73        return 074    int_val = int(val)75    return int_val76def director_list_conv(lst):77    if not lst:78        return []79    return [strutils.to_name(s["name"]) for s in lst]80def list_conv(lst):81    if not lst:82        return []83    return [strutils.to_name(s) for s in lst]84def country_conv(lst):85    if not lst:86        return []87    return [strutils.to_name(s["country"]) for s in lst if s.get("country")]88def uniq_id(vals):89    return "".join(vals)90def location_transformer(sphere, index, row, lst, field, fields):91    val = by_path(row, "location", field.get("json"))92    if not val:93        return94    input = strutils.build_input(val)95    a = utils.to_action(index, "dict", input, input, val.strip(),96                        {"name": strutils.to_name(val),97                         "country": by_path(row, "country",98                                            ["data", "location_tree"])})99    lst[strutils.to_name(val)] = a100def name_transformer(sphere, index, row, lst, field, fields):101    idx = field["name"]102    if not row.get(idx):103        return104    inval = strutils.build_input(row[idx])105    a = utils.to_action(index, "dict", inval, inval, row[idx].strip(),106                        {"id": row["_id"],107                         "name": strutils.to_name(row[idx])})108    lst[strutils.to_name(row[idx])] = a109def object_rating(sphere, index, row, lst, field, fields):110    src = {}111    for field in fields:112        fname = field["name"]113        path = field.get("json")114        if fname in ["_id", "name"]:115            continue116        if fname == "criteria" and row.get(fname):117            val = row[fname]118            for k in val:119                #if k["criterion_id"] == sphere.default_criterion:120                    #src["default"] = k["norm_score"]121                src[k["criterion_id"]] = k["norm_score"]122        elif fname != "criteria":123            conv = field.get("convert", default_conv)124            if path:125                val = by_path(row, fname, field.get("json"))126            else:127                val = row[fname]128            if field.get("filter_name"):129                src["_" + field["filter_name"]] = conv(val)130            else:131                src["_" + fname] = conv(val)132    if sphere.default_criterion not in src:133        src[sphere.default_criterion] = None134    d = {"_index": index,135         "_type": "rating",136         "_id": row["_id"],137         "_source": src}138    lst.append(d)139def country_transformer(sphere, index, row, lst, field, fields):140    val = by_path(row, "country", field.get("json"))141    nval = strutils.to_name(val)142    if not nval:143        return144    input = strutils.build_input(val)145    a = utils.to_action(index, "dict", nval, input, val.strip(),146                        {"name": nval,147                         "path": [nval, "", ""]})148    # only unique values must be appended149    uid = uniq_id([val])150    if uid not in lst:151        lst[uid] = a152def admin1_transformer(sphere, index, row, lst, field, fields):153    val = by_path(row, "admin1", field.get("json"))154    if not val:155        return156    admin1 = strutils.to_name(val)157    country = strutils.to_name(by_path(row, "country", field.get("json")))158    input = strutils.build_input(val)159    a = utils.to_action(index, "dict", admin1, input, val.strip(),160                        {"name": admin1,161                         "path": [country,162                                  admin1,163                                  ""]})164    uid = uniq_id([country if country else "", admin1 if admin1 else ""])165    if uid not in lst:166        lst[uid] = a167def city_transformer(sphere, index, row, lst, field, fields):168    val = by_path(row, "city", field.get("json"))169    input = strutils.build_input(val)170    city = strutils.to_name(val)171    if not city:172        return173    country = strutils.to_name(by_path(row, "country", field.get("json")))174    admin1 = strutils.to_name(by_path(row, "admin1", field.get("json")))175    a = utils.to_action(index, "dict", city, input, val.strip(),176                        {"name": city,177                         "path": [country,178                                  admin1,179                                  city]})180    uid = uniq_id([country if country else "", admin1 if admin1 else "",181                   city if city else ""])182    if uid not in lst:183        lst[uid] = a184def get_from_dict(data, lst):185    from functools import reduce186    return reduce(lambda d, k: d.get(k, {}), lst, data)187def by_path(row, fname, path):188    if path:189        val = get_from_dict(row, path)190        val = val.get(fname)191    else:192        val = row.get(fname)193    return val194def list_transformer(sphere, index, row, lst, field, fields):195    fname = field["name"]196    val = by_path(row, fname, field.get("json"))197    if not val:198        return199    for item in val:200        a = utils.to_action(index, "dict", strutils.to_name(item),201                            strutils.build_input(item), item,202                            {"label": item,203                             "name": strutils.to_name(item)})204        uid = uniq_id([strutils.to_name(item)])205        if uid not in lst:206            lst[uid] = a207def people_transformer(sphere, index, row, acc, field, fields):208    fname = field["name"]209    val = by_path(row, fname, field.get("json"))210    if not val:211        return212    for item in val:213        name = item["name"]214        uid = uniq_id([strutils.to_name(name)])215        if uid not in acc:216            inval = strutils.build_perms(name)217            a = utils.to_action(index, "dict", strutils.to_name(name),218                                inval, name,219                                {"label": name,220                                 "name": strutils.to_name(name)})221            acc[uid] = a222def mcountry_transformer(sphere, index, row, acc, field, fields):223    fname = field["name"]224    val = by_path(row, fname, field.get("json"))225    if not val:226        return227    for item in val:228        name = item["country"]229        uid = uniq_id([strutils.to_name(name)])230        if uid not in acc:231            inval = strutils.to_name(name)232            a = utils.to_action(index, "dict", strutils.to_name(name),233                                inval, name,234                                {"label": name,235                                 "name": strutils.to_name(name)})236            acc[uid] = a237HOTELS_CFG = [238    {"name": "_id", "transformer": object_rating},239    {"name": "name", "transformer": name_transformer},240    {"name": "stars",241     "json": ["data"],242     "object_mapping": {"type": "integer", "store": True},243     "convert": float_floor_conv},244    {"name": "range",245     "filter_name": "price_range",246     "json": ["data", "price"],247     "object_mapping": {"type": "integer", "store": True},248     "convert": int_conv},249    {"name": "location",...Project_Graph_Classes.py
Source:Project_Graph_Classes.py  
1#### 2#### Classes for the project 3####4## Node in a direcetd graph5##  name - string6##  neighbors - dictionary of name: weight7##8import copy9class Node(object):10    def __init__(self, name):11        self.name = name12        self.neighbors = {}13        return(None)14    def __str__(self):15        return "Node name " + str(self.name) + " Neighbors: " + str(self.neighbors)16    def __len__(self):17        # returns the number of neighbors18        return (len(self.neighbors))19    def __contains__(self, item):20        # returns whether item is a name of a neighbor of self.21        try:22            self.neighbors[item]23            return(True)24        except:25            return(False)26    def __getitem__(self, item):27        # returns the weight of the neighbor named key.28        # If there is no such neighbor, then the method returns None29        try:30            return(self.neighbors[item])31        except:32            return(None)33    def __eq__(self, other):34        # based on the name attribute35        try:36            if self.name == other.name:37                return(True)38            else:39                return(False)40        except:41            return(False)42    def __ne__(self, other):43        # based on the name attribute44        try:45            if self.name != other.name:46                return(True)47            else:48                return(False)49        except:50            return(False)51    def is_neighbor(self,name):52        # equivalent to __contains__()53        return(self.__contains__(name))54    def update(self, name, weight=1):55        # adds name as a neighbor of self56        #   If name is not a neighbor of self, then it should be added57        #   If name is already a neighbor of self,58        #       then its weight should be updated to the maximum between the existing weight and weight59        #   This method should not allow adding a neighbor with the same name as self60        if self.name == name:61            return(False)   # can not add self as neighbor62        if self.__contains__(name):63            self.neighbors[name] = max(weight, self.neighbors[name]) #already a neighbor - update weight64        else:65            self.neighbors.update({name:weight}) # add new neighbor66        return(True)67    def remove_neighbors(self, name):68        # removes name from being a neighbor of self69        if name in self.neighbors:70            del self.neighbors[name]71        else:72            return(None)73    def is_isolated(self):74        # returns True if self has no neighbors75        if self.__len__() == 0:76            return(True)77        else:78            return(False)79## Graph is a direcetd graphs based on Node80##81##82##83##84class Graph(object):85    def __init__(self, name, nodes=[]):86        # nodes is an iterable of Node instances87        self.name = name88        self.nodes = {}89        for i in xrange(0, len(nodes)):90            self.nodes.update({nodes[i].name:nodes[i]})91        return(None)92    def __str__(self):93        # print the description of all the nodes in the graph94        returnStr = "\ngraph name: " + str(self.name) + "\n\tNodes: "95        for i in self.nodes:96            returnStr += "\n\t" + str(self.nodes[i])97        return returnStr98    def __len__(self):99        # returns the number of nodes in the graph100        return len(self.nodes)101    def __contains__(self, key):102        # returns True in two cases:103        #   (1) If key is a string, then if a node called key is in self104        #   (2) If key is a Node, then if a node with the same name is in self105        if isinstance(key, basestring): # key is a node name106            if key in self.nodes:107                return True108            else:109                return False110        elif isinstance(key, Node): # key is a Node, extract the Node.name attribute111            if key.name in self.nodes:112                return True113            else:114                return False115    def __getitem__(self, name):116        # returns the Node object whose name is name117        # raises KeyError if name is not in the graph.118        for k in self.nodes:119            if self.nodes[k].name == name:120                return self.nodes[k]121            continue122        # name not found123        raise KeyError124    def update (self, node):125        # adds a new node to the graph126        # node is a Node instance127        if not(self.__contains__(node)):128            # it is a new node129            self.nodes.update({node.name: node})130        else:131            # exiting node132            for n in node.neighbors: # node is in graph. Update its neighbor list133                self.nodes[node.name].update(n, node.neighbors[n])134        return135    def __add__(self, other):136        # returns a new Graph object that includes all the nodes and edges of self and other137        Merged = copy.deepcopy(self) # create a new graph138        for k in other.nodes: # iterate over all nodes of the other graph, and add/update each node139            Merged.update(other.nodes[k])140        return Merged141    def remove_node (self, node):142        # removes the node name from self143        # This method should not fail if name is not in self144        # This method should not remove edges,145        #   Austiin which name is a neighbor of other nodes in the graph.146        self.nodes.pop(node, None) # None assures no failure if node.name does not exist147        return148    def is_edge(self, frm_name, to_name):149        # returns True if to_name is a neighbor of frm_name.150        # This method should not fail if either frm_name or to_name is not in self.151        if self.__contains__(frm_name):152            if self.nodes[frm_name].is_neighbor(to_name):153                return(True)154        return(False)155    def add_edge(self, frm_name, to_name, weight=1):156        # adds an edge making to_name a neighbor of frm_name.157        #   This method applies the same logic as Graph.update().158        #   This method should not fail if either frm_name or to_name are not in self.159        if self.__contains__(frm_name):160            # frm_name is in graph. Update the relevant node in th egraph161            self.nodes[frm_name].update(to_name, weight)162        else:163            # from is not in Graph164            # Create a new Node with its neighbor list165            n =Node(frm_name)166            n.update(to_name, weight)167            self.update(n)168        return169    def remove_edge(self, frm_name, to_name):170        # removes to_name from being a neighbor of frm_name.171        #   This method should not fail if frm_name is not in self.172        #   This method should not fail if to_name is not a neighbor of frm_name.173        if self.__contains__(frm_name):174            self.nodes[frm_name].remove_neighbors(to_name)175        return176    def get_edge_weight(self, frm_name, to_name):177        # returns the weight of the edge between frm_name and to_name178        #   This method should not fail if either frm_name or to_name are not in self.179        #   This method should return None if to_name is not a neighbor of frm_name.180        if self.__contains__(frm_name):181            try:182                return self.nodes[frm_name].__getitem__(to_name) # if to_name does not exist - returns None183            except KeyError:184                return None185        return None186    def get_path_weight(self, path):187        # returns the total weight of the given path, where path is an iterable of nodes' names188        #   This method should return None if the path is not feasible in self.189        #   This method should return None if path is an empty iterable.190        #   Tip: The built-in functions any() and all() regard nonzero numbers as True and None as False.191        Total = 0192        ## if [all(x) for x in Graph[path]193        if len(path) == 0:194            return None195        for n in xrange(0,len(path)-1):196            x = self.get_edge_weight(path[n],path[n+1])197            if not(x):198                return None199            Total += x200        return Total201    def find_all_paths(self, frm_name, to_name, path=[], AllPath=True):202        # Returns a list of paths (each path is a list by itself) from frm_name to to_name203        path = path + [frm_name]204        if frm_name == to_name: # end of recursion - return205            return [path]206        if not (self.__contains__(frm_name)): # error condition207            return []208        paths = []209        for n in self[frm_name].neighbors:210            if n not in path:211                full_paths = self.find_all_paths(n, to_name, path)212                for p in full_paths:213                    paths.append(p)214                    if not(AllPath):215                        return paths # one path found216        return paths217    def is_reachable(self, frm_name, to_name):218        # returns True if to_name is reachable from frm_name.219        #   This method should not fail if either frm_name or to_name are not in self.220        if frm_name == to_name:221            return True222        if not(self.__contains__(frm_name)):223            return False224        paths = self.find_all_paths(frm_name, to_name)225        if len(paths) > 0:226            return True227        else:228            return False229    def find_shortest_path(self, frm_name, to_name):230        # returns the path from frm_name to to_name which has the minimum total weight,231        #   and the total weight of the path232        #   If not reachable retuen [], 0233        all_paths = [([],0)]234        if frm_name == to_name:235            return all_paths[0][0], all_paths[0][1]236        if not(self.__contains__(frm_name)):237            return all_paths[0][0], all_paths[0][1]238        paths = self.find_all_paths(frm_name, to_name)239        for p in paths:240            all_paths.append((p, self.get_path_weight(p)))241        all_paths = sorted(all_paths, key=lambda path_desc: path_desc[1]) # sort by weight242        if len(all_paths)>1: # path found243            return all_paths[1][0], all_paths[1][1]244        else: # no path found245            return all_paths[0][0], all_paths[0][1]246    def find_all_paths(self, frm_name, to_name, path=[]):247        path = path + [frm_name]248        if frm_name == to_name:249            return [path]250        if not (self.__contains__(frm_name)):251            return []252        paths = []253        for vertex in self[frm_name].neighbors:254            if vertex not in path:255                extended_paths = self.find_all_paths(vertex,256                                                     to_name,257                                                     path)258                for p in extended_paths:259                    paths.append(p)...migrations.py
Source:migrations.py  
1import warnings2from functools import wraps3from napari.utils.translations import trans4def rename_argument(from_name: str, to_name: str, version: str):5    """6    This is decorator for simple rename function argument7    without break backward compatibility.8    Parameters9    ----------10    from_name : str11        old name of argument12    to_name : str13        new name of argument14    """15    def _wrapper(func):16        @wraps(func)17        def _update_from_dict(*args, **kwargs):18            if from_name in kwargs:19                if to_name in kwargs:20                    raise ValueError(21                        trans._(22                            "Argument {to_name} already defined, please do not mix {from_name} and {to_name} in one call.",23                            from_name=from_name,24                            to_name=to_name,25                        )26                    )27                warnings.warn(28                    trans._(29                        "Argument {from_name} is deprecated, please use {to_name} instead. It will be removed in {version}.",30                        from_name=from_name,31                        to_name=to_name,32                        version=version,33                    ),34                    category=DeprecationWarning,35                    stacklevel=2,36                )37                kwargs = kwargs.copy()38                kwargs[to_name] = kwargs.pop(from_name)39            return func(*args, **kwargs)40        return _update_from_dict...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!!
