Best Python code snippet using lisa_python
matplotlib_backend.py
Source:matplotlib_backend.py
...110 ax.set_xscale("log", base=_cfg["x_log"])111 if "y_log" in _cfg:112 ax.set_yscale("log", base=_cfg["y_log"])113 return ax114 def _pre_handle(self, idx: int = 0, cfg: Optional[Union[PlotCfg, LegendCfg]] = None):115 _cfg = cfg.matplotlib if cfg is not None else {}116 ax, _cfg = self._get_ax(idx, _cfg)117 return ax, _arg_rename_all(_cfg)118 def plot(self, x, y, idx: int = 0, label: Optional[Union[str, List[str]]] = None, cfg: Optional[PlotCfg] = None):119 ax, _cfg = self._pre_handle(idx, cfg)120 ax.plot(x, y, label=label, **_cfg)121 def fill_between(self, x, y1, y2=0, where: Optional[List[bool]] = None,122 idx: int = 0, label: Optional[Union[str, List[str]]] = None, cfg: Optional[PlotCfg] = None):123 ax, _cfg = self._pre_handle(idx, cfg)124 # step : {{'pre', 'post', 'mid'}} é»è®¤ä¸ºNoneï¼å¡«å
æ¯å
æ»çï¼å¼å¯åæ¯é¶æ¢¯ç¶å¡«å
125 ax.fill_between(x, y1, y2, where=where, label=label, **_cfg)126 def bar(self, x, y, bottom=None, idx: int = 0, label: Optional[Union[str, List[str]]] = None,127 cfg: Optional[PlotCfg] = None):128 ax, _cfg = self._pre_handle(idx, cfg)129 ax.bar(x, y, bottom=bottom, label=label, **_cfg)130 def error_bar(self, x, y, x_err=0, y_err=0, idx: int = 0, label: Optional[Union[str, List[str]]] = None,131 cfg: Optional[PlotCfg] = None):132 ax, _cfg = self._pre_handle(idx, cfg)133 if _cfg.get("width"):134 _cfg["elinewidth"] = _cfg.pop("width")135 if _cfg.get("facecolor"):136 _cfg["ecolor"] = _cfg.pop("facecolor")137 ax.errorbar(x, y, xerr=x_err, yerr=y_err, label=label, **_cfg)138 def pie(self, x, y, idx: int = 0, label: Optional[Union[str, List[str]]] = None,139 cfg: Optional[PlotCfg] = None):140 ax, _cfg = self._pre_handle(idx, cfg)141 if "color" in _cfg and isinstance(_cfg["color"], list):142 _cfg["colors"] = _cfg.pop("color")143 ax.pie(y, labels=x, autopct='%1.1f%%', **_cfg)144 def stack_plot(self, x, y, idx: int = 0, label: Optional[Union[str, List[str]]] = None,145 cfg: Optional[PlotCfg] = None):146 ax, _cfg = self._pre_handle(idx, cfg)147 if label is not None:148 _cfg["labels"] = label149 ax.stackplot(x, y, **_cfg)150 def scatter(self, x, y, s=None, c=None, idx: int = 0, label: Optional[str] = None,151 cfg: Optional[PlotCfg] = None):152 ax, _cfg = self._pre_handle(idx, cfg)153 if "color_bar" in _cfg:154 color_bar = _cfg.pop("color_bar")155 else:156 color_bar = False157 if "colors_legend" in _cfg:158 colors_legend = _cfg.pop("colors_legend")159 else:160 colors_legend = False161 if c is not None and "color" in _cfg:162 # ä¿è¯cæ¯coloræ´ä¸ºä¼å
163 _cfg.pop("color")164 if s is None and "markersize" in _cfg:165 s = _cfg.pop("markersize")166 elif "markersize" in _cfg:167 # scatter ä¸æ¯æmarkersizeåæ°ï¼ä½æ¯så·²ç»è®¾ç½®äº168 _cfg.pop("markersize")169 mappable = ax.scatter(x, y, s, c, label=label, **_cfg)170 if color_bar:171 self.fig.colorbar(mappable, ax=ax)172 if colors_legend:173 # å¯ä»¥è¢«ä¹åçlegend设置è¦ç174 ax.legend(*mappable.legend_elements())175 def hist(self, x, bins, density=False, cumulative=False,176 idx: int = 0, label: Optional[str] = None,177 cfg: Optional[PlotCfg] = None):178 ax, _cfg = self._pre_handle(idx, cfg)179 _cfg = _arg_rename(_cfg, "width", "rwidth")180 ax.hist(x, bins=bins, density=density, cumulative=cumulative, label=label, **_cfg)181 def box_plot(self, x, vert=False,182 idx: int = 0, label: Optional[Union[str, List[str]]] = None,183 cfg: Optional[PlotCfg] = None):184 ax, _cfg = self._pre_handle(idx, cfg)185 width = _cfg.get("width")186 if width is not None:187 del _cfg["width"]188 if _cfg:189 _cfg = {"patch_artist": True, "boxprops": _cfg}190 labels = [label] if (label is not None and isinstance(label, str)) else label191 ax.boxplot(x, vert=vert, labels=labels, widths=width,192 showmeans=True, meanprops={'marker': Markers.circle.value["matplotlib"],193 "color": "black",194 "markeredgecolor": "black",195 "markerfacecolor": "black",196 },197 medianprops={'color': 'black'}, **_cfg)198 def violin_plot(self, x, vert=False,199 idx: int = 0, label: Optional[Union[str, List[str]]] = None,200 cfg: Optional[PlotCfg] = None):201 ax, _cfg = self._pre_handle(idx, cfg)202 width = _cfg.get("width")203 if width is not None:204 del _cfg["width"]205 # labels = [label] if (label is not None and isinstance(label, str)) else label206 parts = ax.violinplot(x, vert=vert, widths=width,207 showmeans=False, showmedians=True)208 for pc in parts['bodies']:209 if _cfg.get("facecolor"):210 pc.set_facecolor(_cfg.get("facecolor"))211 if _cfg.get("color"):212 pc.set_edgecolor(_cfg.get("color"))213 if _cfg.get("alpha"):214 pc.set_alpha(_cfg.get("alpha"))215 def im_show(self, img, idx: int = 0, label: Optional[Union[str, List[str]]] = None, cfg: Optional[PlotCfg] = None):216 ax, _cfg = self._pre_handle(idx, cfg)217 cmap = _cfg.get("cmap")218 alpha = _cfg.get("alpha")219 if cmap is not None:220 if "color_bar" in _cfg:221 color_bar = _cfg.pop("color_bar")222 else:223 color_bar = False224 mappable = ax.imshow(img, cmap=cmap, alpha=alpha)225 if color_bar:226 self.fig.colorbar(mappable, ax=ax)227 else:228 ax.imshow(img, alpha=alpha)229 def add_box(self, box, idx: int = 0, label: Optional[Union[str, List[str]]] = None, cfg: Optional[PlotCfg] = None):230 # box231 # ("xyxy", 90, 160, 600, 700)232 # ("xywh", 90, 160, 690, 860)233 ax, _cfg = self._pre_handle(idx, cfg)234 if box[0] == "xyxy":235 x, y, w, h = box[1], box[2], box[3] - box[1], box[4] - box[2]236 elif box[0] == "xywh":237 x, y, w, h = box[1], box[2], box[3], box[4]238 elif box[0] == 'center_wh':239 w, h = box[3], box[4]240 x = box[1] - 0.5 * w241 y = box[2] - 0.5 * h242 else:243 raise ValueError(box)244 facecolor = _cfg.get("facecolor")245 color = _cfg.get("color")246 width = _cfg.get("linewidth")247 fontsize = _cfg.get("fontsize")248 rec = plt.Rectangle(xy=(x, y), width=w, height=h, fill=False, edgecolor=facecolor, linewidth=width)249 ax.add_patch(rec)250 if label:251 ax.text(x, y, label,252 va='center', ha='center', fontsize=fontsize, color=color,253 bbox=dict(facecolor=facecolor, lw=0))254 def mask(self, x: List[Tuple[float, float]], idx: int = 0, label: Optional[Union[str, List[str]]] = None,255 cfg: Optional[PlotCfg] = None):256 ax, _cfg = self._pre_handle(idx, cfg)257 xs, ys = [item for item in zip(*x)]258 facecolor = _cfg.get("facecolor")259 alpha = _cfg.get("alpha")260 ax.fill(xs, ys, color=facecolor, alpha=alpha)261 if label:262 fontsize = _cfg.get("fontsize")263 color = _cfg.get("color")264 _x = sum(xs) / len(xs)265 _y = sum(ys) / len(ys)266 ax.text(_x, _y, label,267 va='center', ha='center', fontsize=fontsize, color=color)268 def mat_show(self, mat, idx: int = 0, label: Optional[Union[str, List[str]]] = None,269 cfg: Optional[PlotCfg] = None):270 ax, _cfg = self._pre_handle(idx, cfg)271 cmap = _cfg.get("cmap")272 mappable = ax.matshow(mat, interpolation=None, aspect='auto', cmap=cmap)273 if "fontsize" in _cfg and "fmt" in _cfg:274 fs = _cfg["fontsize"]275 for i in range(mat.shape[0]):276 for j in range(mat.shape[1]):277 ax.text(x=j, y=i, s=_cfg["fmt"] % mat[i, j], fontsize=fs, va="center", ha='center')278 if cmap is not None:279 if "color_bar" in _cfg and _cfg["color_bar"]:280 self.fig.colorbar(mappable, ax=ax)281 def legend_set(self, idx: int = 0, cfg: Optional[LegendCfg] = None):282 if cfg is not None:283 ax, _cfg = self._pre_handle(idx, cfg)284 ax.legend(**_cfg) # æ¾ç¤ºå¾ä¾285 def show(self):286 # self.fig.show() # ä¼ä¸éªèé287 plt.show()288 def save(self, path: str):289 self.fig.savefig(path)290 def close(self):291 plt.cla() # clean axis292 plt.clf() # clean figure...
base.py
Source:base.py
...21 @abc.abstractmethod22 def _concatenate_prefix_and_suffix_to_value(self) -> str:23 pass24 @abc.abstractmethod25 def _pre_handle(self) -> str:26 raise NotImplementedError27 @abc.abstractmethod28 def handle(self, obj: Model) -> str:29 raise NotImplementedError30class FieldHandler(IFieldHandler):31 def __init__(self, field, prefix="COPY ", suffix=""):32 self.obj = None33 self.name = field34 self.prefix = prefix35 self.suffix = suffix36 def _get_max_length(self) -> Union[int, None]:37 """Return text according to the max_length defined in Django field38 Args:39 obj (Model): A Django model40 field (str): The field name that will want to be found41 Returns:42 int: The maximum length of field43 None: If field has no maximum length44 """45 max_length = None46 field = self.obj._meta.get_field(self.name) # noqa47 if hasattr(field, "max_length"):48 max_length = field.max_length49 return max_length50 def _get_field_from_obj(self) -> str:51 field_value = getattr(self.obj, self.name)52 return field_value53 def _concatenate_prefix_and_suffix_to_value(self) -> str:54 formatted_text = "{prefix}{field_value}{suffix}".format(55 prefix=self.prefix,56 field_value=self._get_field_from_obj(),57 suffix=self.suffix58 )59 return formatted_text60 def _pre_handle(self) -> str:61 return self._concatenate_prefix_and_suffix_to_value()62 def handle(self, obj: Model) -> str:63 self.obj = obj64 return self._pre_handle()[0:self._get_max_length()]65class SlugFieldHandler(FieldHandler):66 def _pre_handle(self):67 result_text = super()._pre_handle()68 return slugify(result_text)69class IHandlers(ABC):70 """A class to handle any field registered71 Args:72 obj (Model): A django model, where we need to extract the field73 fields (List[IFieldHandler]): A list of all fields to be handle74 auto_import_unique_fields (bool): If is True, import all unique fields from model object75 """76 @abc.abstractmethod77 def __init__(self,78 obj: Type[Model],79 fields: List[IFieldHandler],80 auto_import_unique_fields: bool = False):81 pass...
http.py
Source:http.py
...37 else:38 return resrc.getChildWithDefault(path, request)39class HTTPHookService(BaseHTTPHookService):40 """Base class for synchronous non-terminal service."""41 def _pre_handle(self, path, request):42 """This SHOULD be overridden in derived classes."""43 pass44 def getChild(self, path, request):45 self._pre_handle(path, request)46 return self._next_service(path, request)47class HTTPAsyncHookService(BaseHTTPHookService):48 """Base class for asynchronous non-terminal service.49 50 This is useful if you have a hook service that modify the state of the51 application but needs to wait for a callback to fire before the service52 chain can continue, because other services below this hook depends on some53 yet to come side effect.54 55 The callback is only used for flow control -- it should fire with a None56 value, since this value is going to be ignored. 57 58 IT CAN ONLY BE USED WITH A NON STANDARD IMPLEMENTATION OF SITE (see59 provd.servers.http_site.Site).60 61 """62 def _pre_handle(self, path, request):63 """This SHOULD be overridden in derived classes and must return a64 deferred that will eventually fire.65 66 """67 return defer.succeed(None)68 def getChild(self, path, request):69 d = self._pre_handle(path, request)70 d.addCallback(lambda _: self._next_service(path, request))71 return d72class HTTPLogService(HTTPHookService):73 """A small hook service that permits logging of the request."""74 def __init__(self, logger, service):75 """76 logger -- a callable object taking a string as argument77 78 """79 HTTPHookService.__init__(self, service)80 self._logger = logger81 def _pre_handle(self, path, request):82 self._logger(str(path) + ' ---- ' + str(request))83class HTTPNoListingFileService(static.File):84 """Similar to twisted.web.static.File except that instead of listing the85 content of directories, it returns a 403 Forbidden.86 87 """88 _FORBIDDEN_RESOURCE = resource.ErrorPage(http.FORBIDDEN, 'Forbidden',89 'Directory listing not permitted.')90 _NOT_ALLOWED_RESOURCE = resource.ErrorPage(http.NOT_ALLOWED, 'Method Not Allowed',91 'Method not allowed.')92 def directoryListing(self):93 return self._FORBIDDEN_RESOURCE94 def getChild(self, path, request):95 if request.method != 'GET':...
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!!