Best Python code snippet using slash
SemanticSegmentation.py
Source:SemanticSegmentation.py  
1"""2Performs a semantic segmentation task with 19 classes taken from the Cityscapes dataset.3This method creates a function given a model. The function can then be used on data to perform semantic segmentation. 4"""5import torch.nn as nn6import torch7import numpy as np8colors_data = [ [0,  0,  0],9          [128, 64,128],10          [244, 35,232],11          [70, 70, 70],12          [102,102,156],13          [190,153,153],14          [153,153,153],15          [250,170, 30],16          [250,170, 30],17          [107,142, 35],18          [152,251,152],19          [ 70,130,180],20          [220, 20, 60],21          [255,  0,  0],22          [ 0,  0,142],23          [  0,  0, 70],24          [  0,  0, 70],25          [  0, 80,100],26          [  0,  0,230],27          [119, 11, 32] ]28def convert_to_RGB(y):29    """30    Identifies the class by taking the argmax across values.31    Replaces the class id by the corresponding color.32    33    Returns 34        the identified classes `idtfd` with each pixel assigned with a class i.e. shape of (N, C, H, W) with C the class id,35        the colored images `imgs` with each pixel assigned a color corresponding to the class i.e. shape (N, 3, H, W)36    """37    # n_classes = 1938    n_classes = y.shape[1]39    40    # Create color attribution for coloring41    colors = np.array(colors_data[:n_classes])42    print(f"Using {len(colors)} classes.")43    44    # Identify the class45    idtfd = y.argmax(dim=1).numpy()46    # Create the colored images47    imgs = colors[idtfd]48    imgs = imgs.transpose(0, 3, 1, 2)49    50    return idtfd, imgs51def get_semantic_RGB(model):52    """53    Creates a semantic segmentation task for a single model. 54    Returns a fonction that can be used on a list of RGB (3 channels) images.55    56    Note: the code makes use of the model as an implementation of the `torch.nn.Module`.57    58        semantic_task = get_semantic(UNet)59        preds = semantic_task(imgs)60        preds, colored_preds = semantic_task(imgs, get_colored=True)61        preds, classified_preds = semantic_task(imgs, get_classification=True)62    Parameters:63        model: torch.Tensor64            The model to use for the segmentation65    """66    67    if not isinstance(model, nn.Module):68        raise AttributeError("The passed model should be an implementation of the `torch.nn.Module` class.")69    70    def semantic_segmentation_RGB(imgs, get_colored=False, get_classification=False):71        """72        Performs the semantic segmentation task with the input model.73        Note: the code makes use of the model as an implementation of the `torch.nn.Module`.74    75            semantic_task = get_semantic(UNet)76            preds = semantic_task(imgs)77            preds, colored_preds = semantic_task(imgs, get_colored=True)78            preds, classified_preds = semantic_task(imgs, get_classification=True)79            80        Parameters: 81            imgs: torch.Tensor82                The list of RGB images to segment.83            get_colored: bool (default=False)84                Parameter indicating wether to return the colored images as well. One color per class.85            get_classification: bool (default=False)86                Parameter indicating wether to return the classified pixels. Most confident class per pixel.87                88        """89        if not isinstance(imgs, torch.Tensor):90            raise AttributeError("The input for the segmentation task should be a tensor of images.")91        if not imgs.shape[1] == 3 or len(imgs.shape)!=4:92            raise AttributeError("The input should have the following dimensons (N, C, H, W), respectively number of images, channels, height and width.")93        94        # Setting the model in eval mode95        model.eval()96                97        # running the images through the model98        results = model(imgs)99        100        # Identifying class and coloring.101        idtfd, colored = convert_to_RGB(results)102        103        output = [results]104        105        if get_colored:106            output.append(colored)107        if get_classification:108            output.append(idtfd)109        if len(output)==1:110            return output[0]111        return output112        ...cfparser.py
Source:cfparser.py  
...39    for s in sample_test_o:40        sto.append(s.get_text().replace('Output',''))41    tab = '    '42    paged = '\n'43    paged += get_colored(tab+title, "blue")+"\n"44    paged += get_colored(tab+"Time: ",'blue')+get_colored(time_limit, color='magenta')+"\n"45    paged += get_colored(tab+"Memory: ",'blue')+get_colored(mem_limit, color='magenta')+"\n\n\n"46    paged += get_colored(tab+"Problem Statement:\n", 'blue')+"\n"47    for s in state:48        paged += get_colored(tab+"".join(textwrap.wrap(s, 150))+"\n")+"\n"49    paged += get_colored(tab+"Input:\n", 'blue')+"\n"50    for s in input_s:51        paged += get_colored(tab+"".join(textwrap.wrap(s, 150))+"\n")+"\n"52    paged += get_colored(tab+"Output:\n", 'blue')+"\n"53    for s in output_s:54        paged += get_colored(tab+"\n\t".join(textwrap.wrap(s, 150))+"\n")+"\n"55    for i in range(len(sti)):56        paged += get_colored(tab+"Sample Input "+str(i)+":", 'blue')+"\n"57        paged += get_colored(tab+sti[i].replace('\n', '\n\t '), 'cyan')+"\n"58        paged += get_colored(tab+"Sample Output "+str(i)+":", 'blue')+"\n"59        paged += get_colored(tab+sto[i].replace('\n', '\n\t '), 'green')+"\n"60    # print(paged)61    print(LatexNodes2Text().latex_to_text(paged))62    # pydoc.pager(paged)...color_string.py
Source:color_string.py  
1import colorama2import functools3class ColorStringBase(object):4    def get_colored(self):5        raise NotImplementedError() # pragma: no cover6    def __repr__(self):7        return repr(str(self))8    def __add__(self, other):9        return ColorCompoundString(self, other)10    def __radd__(self, other):11        return ColorCompoundString(other, self)12class ColorString(ColorStringBase):13    def __init__(self, string, color):14        super(ColorString, self).__init__()15        self._string = string16        self._color = color17    def __len__(self):18        return len(self._string)19    def ljust(self, *args):20        return ColorString(self._string.ljust(*args), self._color)21    @classmethod22    def get_formatter(cls, color):23        return functools.partial(cls, color=color)24    def __mod__(self, values):25        return ColorString(self._string % values, self._color)26    def __str__(self):27        return str(self._string)28    def get_colored(self):29        return "{}{}{}".format(getattr(colorama.Fore, self._color.upper()), self._string, colorama.Fore.RESET) # pylint: disable=no-member30class ColorCompoundString(ColorStringBase):31    def __init__(self, *strings):32        super(ColorCompoundString, self).__init__()33        self._strings = strings34    def __str__(self):35        return ''.join(str(x) for x in  self._strings)36    def __len__(self):37        return sum(len(s) for s in self._strings)38    def ljust(self):39        raise NotImplementedError() # pragma: no cover40    def get_colored(self):...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!!
