PatchTraces

Prompt:
Implement the Python class `TraceServiceServicer` described below.

Class description:
This file describes an API for collecting and viewing traces and spans within a trace. A Trace is a collection of spans corresponding to a single operation or set of operations for an application. A span is an individual timed event which forms a node of the trace tree. Spans for a single trace may span multiple services.

Method signatures and docstrings:
- def ListTraces(self, request, context): Returns of a list of traces that match the specified filter conditions.
- def GetTrace(self, request, context): Gets a single trace by its ID.
- def PatchTraces(self, request, context): Sends new traces to Stackdriver Trace or updates existing traces. If the ID of a trace that you send matches that of an existing trace, any fields in the existing trace and its spans are overwritten by the provided values, and any new fields provided are merged with the existing trace data. If the ID does not match, a new trace is created.

Implement the Python class `TraceServiceServicer` described below.

Class description:
This file describes an API for collecting and viewing traces and spans within a trace. A Trace is a collection of spans corresponding to a single operation or set of operations for an application. A span is an individual timed event which forms a node of the trace tree. Spans for a single trace may span multiple services.

Method signatures and docstrings:
- def ListTraces(self, request, context): Returns of a list of traces that match the specified filter conditions.
- def GetTrace(self, request, context): Gets a single trace by its ID.
- def PatchTraces(self, request, context): Sends new traces to Stackdriver Trace or updates existing traces. If the ID of a trace that you send matches that of an existing trace, any fields in the existing trace and its spans are overwritten by the provided values, and any new fields provided are merged with the existing trace data. If the ID does not match, a new trace is created.

<|skeleton|>
class TraceServiceServicer:
    """This file describes an API for collecting and viewing traces and spans within a trace. A Trace is a collection of spans corresponding to a single operation or set of operations for an application. A span is an individual timed event which forms a node of the trace tree. Spans for a single trace may span multiple services."""

    def ListTraces(self, request, context):
        """Returns of a list of traces that match the specified filter conditions."""
        <|body_0|>

    def GetTrace(self, request, context):
        """Gets a single trace by its ID."""
        <|body_1|>

    def PatchTraces(self, request, context):
        """Sends new traces to Stackdriver Trace or updates existing traces. If the ID of a trace that you send matches that of an existing trace, any fields in the existing trace and its spans are overwritten by the provided values, and any new fields provided are merged with the existing trace data. If the ID does not match, a new trace is created."""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details('Method not implemented!')
        raise NotImplementedError('Method not implemented!')
<|end_body_0|>

<|body_start_1|>
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details('Method not implemented!')
        raise NotImplementedError('Method not implemented!')
<|end_body_1|>

<|body_start_2|>
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details('Method not implemented!')
        raise NotImplementedError('Method not implemented!')
<|end_body_2|>

Solution:
class TraceServiceServicer:
    """This file describes an API for collecting and viewing traces and spans within a trace. A Trace is a collection of spans corresponding to a single operation or set of operations for an application. A span is an individual timed event which forms a node of the trace tree. Spans for a single trace may span multiple services."""

    def ListTraces(self, request, context):
        """Returns of a list of traces that match the specified filter conditions."""
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details('Method not implemented!')
        raise NotImplementedError('Method not implemented!')

    def GetTrace(self, request, context):
        """Gets a single trace by its ID."""
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details('Method not implemented!')
        raise NotImplementedError('Method not implemented!')

    def PatchTraces(self, request, context):
        """Sends new traces to Stackdriver Trace or updates existing traces. If the ID of a trace that you send matches that of an existing trace, any fields in the existing trace and its spans are overwritten by the provided values, and any new fields provided are merged with the existing trace data. If the ID does not match, a new trace is created."""
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details('Method not implemented!')
        raise NotImplementedError('Method not implemented!')


filter

Prompt:
Implement the Python class `ExclusionFilter` described below.

Class description:
Filters search results based on a list of words to exclude, if any of these are found the result in question is rejected. Options: * order (int): defines when, in the pipeline, this filter will be executed * terms (str): terms that, if appearing in the result, will cause it to be rejected - separated by "+'s" * customFields (list of str): extra fields in the results to filter with the exclusion list - depedendent upon their existence in the search service results

Method signatures and docstrings:
- def __init__(self, order=0, terms='', customFields=[]): Constructor for ExclusionFilter.
- def matches_exclusion_list(self, input_string): Removes results that includes words contained in exclusion list. Parameters: * exclusion_list_string: terms which, if found, will cause a result to be rejected * input_string: string with words separated by blank spaces i.e. the result field being checked for terms from the exclusion list Returns: * true: if any of the words of the input string is included in the exclusion list false: in other case
- def filter(self, results): Filters the results according to exclusion list - rejecting results containing offending words. Parameters: * results (puppy.model.Opensearch.Response): results to be filtered Returns: * results_returned (puppy.model.Opensearch.Response): filtered results

Implement the Python class `ExclusionFilter` described below.

Class description:
Filters search results based on a list of words to exclude, if any of these are found the result in question is rejected. Options: * order (int): defines when, in the pipeline, this filter will be executed * terms (str): terms that, if appearing in the result, will cause it to be rejected - separated by "+'s" * customFields (list of str): extra fields in the results to filter with the exclusion list - depedendent upon their existence in the search service results

Method signatures and docstrings:
- def __init__(self, order=0, terms='', customFields=[]): Constructor for ExclusionFilter.
- def matches_exclusion_list(self, input_string): Removes results that includes words contained in exclusion list. Parameters: * exclusion_list_string: terms which, if found, will cause a result to be rejected * input_string: string with words separated by blank spaces i.e. the result field being checked for terms from the exclusion list Returns: * true: if any of the words of the input string is included in the exclusion list false: in other case
- def filter(self, results): Filters the results according to exclusion list - rejecting results containing offending words. Parameters: * results (puppy.model.Opensearch.Response): results to be filtered Returns: * results_returned (puppy.model.Opensearch.Response): filtered results

<|skeleton|>
class ExclusionFilter:
    """Filters search results based on a list of words to exclude, if any of these are found the result in question is rejected. Options: * order (int): defines when, in the pipeline, this filter will be executed * terms (str): terms that, if appearing in the result, will cause it to be rejected - separated by "+'s" * customFields (list of str): extra fields in the results to filter with the exclusion list - depedendent upon their existence in the search service results"""

    def __init__(self, order=0, terms='', customFields=[]):
        """Constructor for ExclusionFilter."""
        <|body_0|>

    def matches_exclusion_list(self, input_string):
        """Removes results that includes words contained in exclusion list. Parameters: * exclusion_list_string: terms which, if found, will cause a result to be rejected * input_string: string with words separated by blank spaces i.e. the result field being checked for terms from the exclusion list Returns: * true: if any of the words of the input string is included in the exclusion list false: in other case"""
        <|body_1|>

    def filter(self, results):
        """Filters the results according to exclusion list - rejecting results containing offending words. Parameters: * results (puppy.model.Opensearch.Response): results to be filtered Returns: * results_returned (puppy.model.Opensearch.Response): filtered results"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        super(ExclusionFilter, self).__init__(order)
        self.info = 'Filters search results based on a exclusion list.'
        self.exclusion_list_string = ' '.join(filter(str.isalpha, terms.replace('+', ' ').lower().split()))
        self.filter_fields = ['title', 'summary']
        for field in customFields:
            self.filter_fields.append(field)
<|end_body_0|>

<|body_start_1|>
        input_list = input_string.split()
        exclusion_list = self.exclusion_list_string.split()
        for input in input_list:
            try:
                input_filtered = ''.join(filter(str.isalpha, list(input.lower())))
            except TypeError:
                tmp = input.encode('utf-8').lower()
                input_filtered = ''.join(filter(str.isalpha, list(tmp)))
            if input_filtered in exclusion_list:
                if input_filtered not in ' ':
                    return True
        return False
<|end_body_1|>

<|body_start_2|>
        def fieldValid(result, field):
            """ This method checks the custom field exists and is also of format str/unicode """
            if result.has_key(field):
                if type(result[field]) == str or type(result[field]) == unicode:
                    return True
                else:
                    print('Error: custom field {0} was of {1} instead of str/unicode'.format(field, type(result[field])))
                    return False
            else:
                print('Error: custom field {0} was not found in the results'.format(field))
                return False
        for result in results:
            valid = True
            for field in self.filter_fields:
                if fieldValid(result, field):
                    valid = not self.matches_exclusion_list(result[field])
                if valid == False:
                    break
            if valid == True:
                yield result
<|end_body_2|>

Solution:
class ExclusionFilter:
    """Filters search results based on a list of words to exclude, if any of these are found the result in question is rejected. Options: * order (int): defines when, in the pipeline, this filter will be executed * terms (str): terms that, if appearing in the result, will cause it to be rejected - separated by "+'s" * customFields (list of str): extra fields in the results to filter with the exclusion list - depedendent upon their existence in the search service results"""

    def __init__(self, order=0, terms='', customFields=[]):
        """Constructor for ExclusionFilter."""
        super(ExclusionFilter, self).__init__(order)
        self.info = 'Filters search results based on a exclusion list.'
        self.exclusion_list_string = ' '.join(filter(str.isalpha, terms.replace('+', ' ').lower().split()))
        self.filter_fields = ['title', 'summary']
        for field in customFields:
            self.filter_fields.append(field)

    def matches_exclusion_list(self, input_string):
        """Removes results that includes words contained in exclusion list. Parameters: * exclusion_list_string: terms which, if found, will cause a result to be rejected * input_string: string with words separated by blank spaces i.e. the result field being checked for terms from the exclusion list Returns: * true: if any of the words of the input string is included in the exclusion list false: in other case"""
        input_list = input_string.split()
        exclusion_list = self.exclusion_list_string.split()
        for input in input_list:
            try:
                input_filtered = ''.join(filter(str.isalpha, list(input.lower())))
            except TypeError:
                tmp = input.encode('utf-8').lower()
                input_filtered = ''.join(filter(str.isalpha, list(tmp)))
            if input_filtered in exclusion_list:
                if input_filtered not in ' ':
                    return True
        return False

    def filter(self, results):
        """Filters the results according to exclusion list - rejecting results containing offending words. Parameters: * results (puppy.model.Opensearch.Response): results to be filtered Returns: * results_returned (puppy.model.Opensearch.Response): filtered results"""
        def fieldValid(result, field):
            """ This method checks the custom field exists and is also of format str/unicode """
            if result.has_key(field):
                if type(result[field]) == str or type(result[field]) == unicode:
                    return True
                else:
                    print('Error: custom field {0} was of {1} instead of str/unicode'.format(field, type(result[field])))
                    return False
            else:
                print('Error: custom field {0} was not found in the results'.format(field))
                return False
        for result in results:
            valid = True
            for field in self.filter_fields:
                if fieldValid(result, field):
                    valid = not self.matches_exclusion_list(result[field])
                if valid == False:
                    break
            if valid == True:
                yield result


report

Prompt:
Implement the Python class `Reporter` described below.

Class description:
Implement the Reporter class.

Method signatures and docstrings:
- def __init__(self, builder): @types: file_topology.Builder @raise ValueError: Builder is not specified
- def report(self, file_, containerOsh): @types: File, ObjectStateHolder -> ObjectStateHolder @raise ValueError: Container is not specified

Implement the Python class `Reporter` described below.

Class description:
Implement the Reporter class.

Method signatures and docstrings:
- def __init__(self, builder): @types: file_topology.Builder @raise ValueError: Builder is not specified
- def report(self, file_, containerOsh): @types: File, ObjectStateHolder -> ObjectStateHolder @raise ValueError: Container is not specified

<|skeleton|>
class Reporter:

    def __init__(self, builder):
        """@types: file_topology.Builder @raise ValueError: Builder is not specified"""
        <|body_0|>

    def report(self, file_, containerOsh):
        """@types: File, ObjectStateHolder -> ObjectStateHolder @raise ValueError: Container is not specified"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        if not builder:
            raise ValueError('Builder is not specified')
        self.__builder = builder
<|end_body_0|>

<|body_start_1|>
        if not containerOsh:
            raise ValueError('Container is not specified')
        osh = self.__builder.buildFile(file_)
        osh.setContainer(containerOsh)
        return osh
<|end_body_1|>

Solution:
class Reporter:
    def __init__(self, builder):
        """@types: file_topology.Builder @raise ValueError: Builder is not specified"""
        if not builder:
            raise ValueError('Builder is not specified')
        self.__builder = builder

    def report(self, file_, containerOsh):
        """@types: File, ObjectStateHolder -> ObjectStateHolder @raise ValueError: Container is not specified"""
        if not containerOsh:
            raise ValueError('Container is not specified')
        osh = self.__builder.buildFile(file_)
        osh.setContainer(containerOsh)
        return osh


Prompt:
Implement the Python class `LundDatasetLoader` described below.

Class description:
Simple loader class that reads from a folder on disk. Folder layout structure: - RGB Images: images/ - Extrinsics data (optional): extrinsics/ - numpy array with the same name as images If explicit intrinsics are not provided, the exif data will be used.

Method signatures and docstrings:
- def __init__(self, folder: str) -> None: Initialize object to load image data from a specified folder on disk Args: folder: the base folder for a given scene.
- def __generate_extrinsics_from_reconstruction(self) -> List[str]: Extract extrinsics from mat file and stores them as numpy arrays. The reconstruction used for extrinsics is provided by Carl Olsson as part of the Lund dataset. Returns: file names of generated extrinsics for each pose.

Implement the Python class `LundDatasetLoader` described below.

Class description:
Simple loader class that reads from a folder on disk. Folder layout structure: - RGB Images: images/ - Extrinsics data (optional): extrinsics/ - numpy array with the same name as images If explicit intrinsics are not provided, the exif data will be used.

Method signatures and docstrings:
- def __init__(self, folder: str) -> None: Initialize object to load image data from a specified folder on disk Args: folder: the base folder for a given scene.
- def __generate_extrinsics_from_reconstruction(self) -> List[str]: Extract extrinsics from mat file and stores them as numpy arrays. The reconstruction used for extrinsics is provided by Carl Olsson as part of the Lund dataset. Returns: file names of generated extrinsics for each pose.

<|skeleton|>
class LundDatasetLoader:
    """Simple loader class that reads from a folder on disk. Folder layout structure: - RGB Images: images/ - Extrinsics data (optional): extrinsics/ - numpy array with the same name as images If explicit intrinsics are not provided, the exif data will be used."""

    def __init__(self, folder: str) -> None:
        """Initialize object to load image data from a specified folder on disk Args: folder: the base folder for a given scene."""
        <|body_0|>

    def __generate_extrinsics_from_reconstruction(self) -> List[str]:
        """Extract extrinsics from mat file and stores them as numpy arrays. The reconstruction used for extrinsics is provided by Carl Olsson as part of the Lund dataset. Returns: file names of generated extrinsics for each pose."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.folder_base = folder
        super().__init__(folder, image_extension='JPG')
        if not self.explicit_extrinsics_paths:
            self.explicit_extrinsics_paths = self.__generate_extrinsics_from_reconstruction()
<|end_body_0|>

<|body_start_1|>
        reconstruction_path = os.path.join(self.folder_base, 'reconstruction', 'data.mat')
        extrinsics_path_template = os.path.join(self.folder_base, 'extrinsics', '{}.npy')
        loaded_data = scipy_io.loadmat(reconstruction_path)
        image_names = loaded_data['imnames']
        poses = loaded_data['P'][0]
        num_images = image_names.shape[0]
        filenames = []
        for idx in range(num_images):
            image_name = image_names[idx][0][0][0]
            image_name = os.path.splitext(image_name)[0]
            extrinsics = poses[idx]
            filename = extrinsics_path_template.format(image_name)
            np.save(filename, extrinsics)
            filenames.append(filename)
        return filenames
<|end_body_1|>

Solution:
class LundDatasetLoader:
    """Simple loader class that reads from a folder on disk. Folder layout structure: - RGB Images: images/ - Extrinsics data (optional): extrinsics/ - numpy array with the same name as images If explicit intrinsics are not provided, the exif data will be used."""

    def __init__(self, folder: str) -> None:
        """Initialize object to load image data from a specified folder on disk Args: folder: the base folder for a given scene."""
        self.folder_base = folder
        super().__init__(folder, image_extension='JPG')
        if not self.explicit_extrinsics_paths:
            self.explicit_extrinsics_paths = self.__generate_extrinsics_from_reconstruction()

    def __generate_extrinsics_from_reconstruction(self) -> List[str]:
        """Extract extrinsics from mat file and stores them as numpy arrays. The reconstruction used for extrinsics is provided by Carl Olsson as part of the Lund dataset. Returns: file names of generated extrinsics for each pose."""
        reconstruction_path = os.path.join(self.folder_base, 'reconstruction', 'data.mat')
        extrinsics_path_template = os.path.join(self.folder_base, 'extrinsics', '{}.npy')
        loaded_data = scipy_io.loadmat(reconstruction_path)
        image_names = loaded_data['imnames']
        poses = loaded_data['P'][0]
        num_images = image_names.shape[0]
        filenames = []
        for idx in range(num_images):
            image_name = image_names[idx][0][0][0]
            image_name = os.path.splitext(image_name)[0]
            extrinsics = poses[idx]
            filename = extrinsics_path_template.format(image_name)
            np.save(filename, extrinsics)
            filenames.append(filename)
        return filenames


Prompt:
Implement the Python class `StfNERTagger` described below.

Class description:
Implement the StfNERTagger class.

Method signatures and docstrings:
- def __init__(self): Open client for Stanford NERTagger :return: protocol open
- def identify_person_types(self, text: str) -> list: Users Stanford NERTagger to identify person types. It cleans-up some unwanted chars to have better accuracy :param text: text to identify types :return: list

Implement the Python class `StfNERTagger` described below.

Class description:
Implement the StfNERTagger class.

Method signatures and docstrings:
- def __init__(self): Open client for Stanford NERTagger :return: protocol open
- def identify_person_types(self, text: str) -> list: Users Stanford NERTagger to identify person types. It cleans-up some unwanted chars to have better accuracy :param text: text to identify types :return: list

<|skeleton|>
class StfNERTagger:

    def __init__(self):
        """Open client for Stanford NERTagger :return: protocol open"""
        <|body_0|>

    def identify_person_types(self, text: str) -> list:
        """Users Stanford NERTagger to identify person types. It cleans-up some unwanted chars to have better accuracy :param text: text to identify types :return: list"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        ser_path = get_project_path() + '/nltk_libs/english.all.3class.distsim.crf.ser'
        jar_path = get_project_path() + '/nltk_libs/stanford-ner-3.8.0.jar'
        self.st = StanfordNERTagger(ser_path, jar_path)
<|end_body_0|>

<|body_start_1|>
        cleaned_text = CleanComments.filter_special_characters(comment=text)
        words = cleaned_text.strip().split()
        tags = []
        try:
            tags = self.st.tag(words)
        except Exception as e:
            logger.warning(msg='Error identifying entities using Stanford: %s ' % str(e))
        return [tag[0].lower() for tag in tags if tag[1] == 'PERSON']
<|end_body_1|>

Solution:
class StfNERTagger:
    def __init__(self):
        """Open client for Stanford NERTagger :return: protocol open"""
        ser_path = get_project_path() + '/nltk_libs/english.all.3class.distsim.crf.ser'
        jar_path = get_project_path() + '/nltk_libs/stanford-ner-3.8.0.jar'
        self.st = StanfordNERTagger(ser_path, jar_path)

    def identify_person_types(self, text: str) -> list:
        """Users Stanford NERTagger to identify person types. It cleans-up some unwanted chars to have better accuracy :param text: text to identify types :return: list"""
        cleaned_text = CleanComments.filter_special_characters(comment=text)
        words = cleaned_text.strip().split()
        tags = []
        try:
            tags = self.st.tag(words)
        except Exception as e:
            logger.warning(msg='Error identifying entities using Stanford: %s ' % str(e))
        return [tag[0].lower() for tag in tags if tag[1] == 'PERSON']


shortest

Prompt:
Implement the Python class `WordDistance` described below.

Class description:
Implement the WordDistance class.

Method signatures and docstrings:
- def __init__(self, wordsDict): :type wordsDict: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int

Implement the Python class `WordDistance` described below.

Class description:
Implement the WordDistance class.

Method signatures and docstrings:
- def __init__(self, wordsDict): :type wordsDict: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int

<|skeleton|>
class WordDistance:

    def __init__(self, wordsDict):
        """:type wordsDict: List[str]"""
        <|body_0|>

    def shortest(self, word1, word2):
        """:type word1: str :type word2: str :rtype: int"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.dict = {}
        for i in range(len(wordsDict)):
            if wordsDict[i] in self.dict:
                self.dict[wordsDict[i]].append(i)
            else:
                self.dict[wordsDict[i]] = [i]
        for k in self.dict:
            self.dict[k].sort()
        self.mindist = {}
<|end_body_0|>

<|body_start_1|>
        if word1 + '_' + word2 in self.mindist:
            return self.mindist['word1' + '_' + 'word2']
        if word2 + '_' + word1 in self.mindist:
            return self.mindist['word2' + '_' + 'word1']
        q = 0
        p = 0
        mindist = float('inf')
        while q < len(self.dict[word2]):
            v2 = self.dict[word2][q]
            while p <= len(self.dict[word1]):
                v1 = self.dict[word1][p] if p == len(self.dict[word1]) else float('inf')
                prev1 = self.dict[word1][p - 1] if p > 0 else -float('inf')
                if v2 <= v1 and v2 >= prev1:
                    mindist = min(mindist, abs(v2 - v1), abs(v2 - prev1))
                    break
                p += 1
            q += 1
        self.mindist['word2' + '_' + 'word1'] = mindist
        self.mindist['word1' + '_' + 'word2'] = mindist
        return mindist
<|end_body_1|>

Solution:
class WordDistance:
    def __init__(self, wordsDict):
        """:type wordsDict: List[str]"""
        self.dict = {}
        for i in range(len(wordsDict)):
            if wordsDict[i] in self.dict:
                self.dict[wordsDict[i]].append(i)
            else:
                self.dict[wordsDict[i]] = [i]
        for k in self.dict:
            self.dict[k].sort()
        self.mindist = {}

    def shortest(self, word1, word2):
        """:type word1: str :type word2: str :rtype: int"""
        if word1 + '_' + word2 in self.mindist:
            return self.mindist['word1' + '_' + 'word2']
        if word2 + '_' + word1 in self.mindist:
            return self.mindist['word2' + '_' + 'word1']
        q = 0
        p = 0
        mindist = float('inf')
        while q < len(self.dict[word2]):
            v2 = self.dict[word2][q]
            while p <= len(self.dict[word1]):
                v1 = self.dict[word1][p] if p == len(self.dict[word1]) else float('inf')
                prev1 = self.dict[word1][p - 1] if p > 0 else -float('inf')
                if v2 <= v1 and v2 >= prev1:
                    mindist = min(mindist, abs(v2 - v1), abs(v2 - prev1))
                    break
                p += 1
            q += 1
        self.mindist['word2' + '_' + 'word1'] = mindist
        self.mindist['word1' + '_' + 'word2'] = mindist
        return mindist


bind

Prompt:
Implement the Python class `FlowItem` described below.

Class description:
A widget which can be used as an item in a FlowArea. A FlowItem is a widget which can be used as a child of a FlowArea widget. It can have at most a single child widget which is an instance of Container.

Method signatures and docstrings:
- def snapshot(self): Returns the snapshot dict for the FlowItem.
- def bind(self): Bind the change handler for the FlowItem.
- def _get_flow_widget(self): The getter for the 'flow_widget' property. Returns ------- result : Container or None The flow widget for the FlowItem, or None if not provided.

Implement the Python class `FlowItem` described below.

Class description:
A widget which can be used as an item in a FlowArea. A FlowItem is a widget which can be used as a child of a FlowArea widget. It can have at most a single child widget which is an instance of Container.

Method signatures and docstrings:
- def snapshot(self): Returns the snapshot dict for the FlowItem.
- def bind(self): Bind the change handler for the FlowItem.
- def _get_flow_widget(self): The getter for the 'flow_widget' property. Returns ------- result : Container or None The flow widget for the FlowItem, or None if not provided.

<|skeleton|>
class FlowItem:
    """A widget which can be used as an item in a FlowArea. A FlowItem is a widget which can be used as a child of a FlowArea widget. It can have at most a single child widget which is an instance of Container."""

    def snapshot(self):
        """Returns the snapshot dict for the FlowItem."""
        <|body_0|>

    def bind(self):
        """Bind the change handler for the FlowItem."""
        <|body_1|>

    def _get_flow_widget(self):
        """The getter for the 'flow_widget' property. Returns ------- result : Container or None The flow widget for the FlowItem, or None if not provided."""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        snap = super(FlowItem, self).snapshot()
        snap['preferred_size'] = self.preferred_size
        snap['align'] = self.align
        snap['stretch'] = self.stretch
        snap['ortho_stretch'] = self.ortho_stretch
        return snap
<|end_body_0|>

<|body_start_1|>
        super(FlowItem, self).bind()
        attrs = ('preferred_size', 'align', 'stretch', 'ortho_stretch')
        self.publish_attributes(*attrs)
<|end_body_1|>

<|body_start_2|>
        widget = None
        for child in self.children:
            if isinstance(child, Container):
                widget = child
        return widget
<|end_body_2|>

Solution:
class FlowItem:
    """A widget which can be used as an item in a FlowArea. A FlowItem is a widget which can be used as a child of a FlowArea widget. It can have at most a single child widget which is an instance of Container."""

    def snapshot(self):
        """Returns the snapshot dict for the FlowItem."""
        snap = super(FlowItem, self).snapshot()
        snap['preferred_size'] = self.preferred_size
        snap['align'] = self.align
        snap['stretch'] = self.stretch
        snap['ortho_stretch'] = self.ortho_stretch
        return snap

    def bind(self):
        """Bind the change handler for the FlowItem."""
        super(FlowItem, self).bind()
        attrs = ('preferred_size', 'align', 'stretch', 'ortho_stretch')
        self.publish_attributes(*attrs)

    def _get_flow_widget(self):
        """The getter for the 'flow_widget' property. Returns ------- result : Container or None The flow widget for the FlowItem, or None if not provided."""
        widget = None
        for child in self.children:
            if isinstance(child, Container):
                widget = child
        return widget


查询阿里云redis信息

DescribeInstances

Prompt:
Implement the Python class `ALiYunApiRedis` described below.

Class description:
查询阿里云redis信息

Method signatures and docstrings:
- def DescribeInstances(self, config): 调用该API可以查询账户下的某一个或多个实例信息。。 :param config: :return:
- def DescribeInstanceAttribute(self, config): 调用该API可以查询账户下的某一个或多个实例信息。。 :param config: :return:

Implement the Python class `ALiYunApiRedis` described below.

Class description:
查询阿里云redis信息

Method signatures and docstrings:
- def DescribeInstances(self, config): 调用该API可以查询账户下的某一个或多个实例信息。。 :param config: :return:
- def DescribeInstanceAttribute(self, config): 调用该API可以查询账户下的某一个或多个实例信息。。 :param config: :return:

<|skeleton|>
class ALiYunApiRedis:
    """查询阿里云redis信息"""

    def DescribeInstances(self, config):
        """调用该API可以查询账户下的某一个或多个实例信息。。 :param config: :return:"""
        <|body_0|>

    def DescribeInstanceAttribute(self, config):
        """调用该API可以查询账户下的某一个或多个实例信息。。 :param config: :return:"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.aliyunrequest.set_action_name('DescribeInstances')
        if not isinstance(config, list):
            return self.MResponse(code=20001, msg='config配置不正确', status=False)
        self.Mconfig(config)
        response = self.aliyunapiclient.do_action_with_exception(self.aliyunrequest)
        return response
<|end_body_0|>

<|body_start_1|>
        self.aliyunrequest.set_action_name('DescribeInstanceAttribute')
        if not isinstance(config, list):
            return self.MResponse(code=20001, msg='config配置不正确', status=False)
        self.Mconfig(config)
        response = self.aliyunapiclient.do_action_with_exception(self.aliyunrequest)
        return response
<|end_body_1|>

Solution:
class ALiYunApiRedis:
    """查询阿里云redis信息"""

    def DescribeInstances(self, config):
        """调用该API可以查询账户下的某一个或多个实例信息。。 :param config: :return:"""
        self.aliyunrequest.set_action_name('DescribeInstances')
        if not isinstance(config, list):
            return self.MResponse(code=20001, msg='config配置不正确', status=False)
        self.Mconfig(config)
        response = self.aliyunapiclient.do_action_with_exception(self.aliyunrequest)
        return response

    def DescribeInstanceAttribute(self, config):
        """调用该API可以查询账户下的某一个或多个实例信息。。 :param config: :return:"""
        self.aliyunrequest.set_action_name('DescribeInstanceAttribute')
        if not isinstance(config, list):
            return self.MResponse(code=20001, msg='config配置不正确', status=False)
        self.Mconfig(config)
        response = self.aliyunapiclient.do_action_with_exception(self.aliyunrequest)
        return response


getClient

Prompt:
Implement the Python class `Client` described below.

Class description:
Implement the Client class.

Method signatures and docstrings:
- def getUrl(api) -> str: Provide the base url to access the specific API. :param str api: The specific API for which we need the base url. return: The requested base url rtype str
- def getClient(api, api_key): Provide the required Client instance to interact with the specific API. :param str api: The specific API we need to interact with. :param str api_key: The API key to authenticate the request bwing made. return: The requested Client instance. rtype str

Implement the Python class `Client` described below.

Class description:
Implement the Client class.

Method signatures and docstrings:
- def getUrl(api) -> str: Provide the base url to access the specific API. :param str api: The specific API for which we need the base url. return: The requested base url rtype str
- def getClient(api, api_key): Provide the required Client instance to interact with the specific API. :param str api: The specific API we need to interact with. :param str api_key: The API key to authenticate the request bwing made. return: The requested Client instance. rtype str

<|skeleton|>
class Client:

    def getUrl(api) -> str:
        """Provide the base url to access the specific API. :param str api: The specific API for which we need the base url. return: The requested base url rtype str"""
        <|body_0|>

    def getClient(api, api_key):
        """Provide the required Client instance to interact with the specific API. :param str api: The specific API we need to interact with. :param str api_key: The API key to authenticate the request bwing made. return: The requested Client instance. rtype str"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        url: str = ''
        if api == 'Detections':
            url = 'https://detections.icebrg.io/v1/'
        elif api == 'Sensors':
            url = 'https://sensor.icebrg.io/v1/'
        elif api == 'Entity':
            url = 'https://entity.icebrg.io/v1/entity/'
        return url
<|end_body_0|>

<|body_start_1|>
        headers = {'Authorization': 'IBToken ' + api_key, 'User-Agent': 'Cortex_Insight.v3', 'Content-Type': 'application/json'}
        match api:
            case 'Entity':
                return EntityClient(base_url=Client.getUrl(api), headers=headers)
            case 'Sensors':
                return SensorClient(base_url=Client.getUrl(api), headers=headers)
            case 'Detections':
                return DetectionClient(base_url=Client.getUrl(api), headers=headers)
<|end_body_1|>

Solution:
class Client:
    def getUrl(api) -> str:
        """Provide the base url to access the specific API. :param str api: The specific API for which we need the base url. return: The requested base url rtype str"""
        url: str = ''
        if api == 'Detections':
            url = 'https://detections.icebrg.io/v1/'
        elif api == 'Sensors':
            url = 'https://sensor.icebrg.io/v1/'
        elif api == 'Entity':
            url = 'https://entity.icebrg.io/v1/entity/'
        return url

    def getClient(api, api_key):
        """Provide the required Client instance to interact with the specific API. :param str api: The specific API we need to interact with. :param str api_key: The API key to authenticate the request bwing made. return: The requested Client instance. rtype str"""
        headers = {'Authorization': 'IBToken ' + api_key, 'User-Agent': 'Cortex_Insight.v3', 'Content-Type': 'application/json'}
        match api:
            case 'Entity':
                return EntityClient(base_url=Client.getUrl(api), headers=headers)
            case 'Sensors':
                return SensorClient(base_url=Client.getUrl(api), headers=headers)
            case 'Detections':
                return DetectionClient(base_url=Client.getUrl(api), headers=headers)


Prompt:
Implement the Python class `ZigzagIterator` described below.

Class description:
Implement the ZigzagIterator class.

Method signatures and docstrings:
- def __init__(self, v1, v2): Initialize your data structure here. :type v1: List[int] :type v2: List[int]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bool

Implement the Python class `ZigzagIterator` described below.

Class description:
Implement the ZigzagIterator class.

Method signatures and docstrings:
- def __init__(self, v1, v2): Initialize your data structure here. :type v1: List[int] :type v2: List[int]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bool

<|skeleton|>
class ZigzagIterator:

    def __init__(self, v1, v2):
        """Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
        <|body_0|>

    def next(self):
        """:rtype: int"""
        <|body_1|>

    def hasNext(self):
        """:rtype: bool"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        self.v = [v1, v2]
        self.n = [len(v1), len(v2)]
        self.row = 1
        self.col = -1
<|end_body_0|>

<|body_start_1|>
        if self.row == 1:
            self.row = 0 if self.col + 1 < self.n[0] else 1
            self.col += 1
        elif self.col < self.n[1]:
            self.row = 1
        else:
            self.col += 1
        return self.v[self.row][self.col]
<|end_body_1|>

<|body_start_2|>
        if self.row == 1:
            if self.col + 1 < self.n[0]:
                row_next = 0
                col_next = self.col + 1
            else:
                row_next = 1
                col_next = self.col + 1
        elif self.col < self.n[1]:
            row_next = 1
            col_next = self.col
        else:
            row_next = 0
            col_next = self.col + 1
        return col_next < self.n[row_next]
<|end_body_2|>

Solution:
class ZigzagIterator:
    def __init__(self, v1, v2):
        """Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
        self.v = [v1, v2]
        self.n = [len(v1), len(v2)]
        self.row = 1
        self.col = -1

    def next(self):
        """:rtype: int"""
        if self.row == 1:
            self.row = 0 if self.col + 1 < self.n[0] else 1
            self.col += 1
        elif self.col < self.n[1]:
            self.row = 1
        else:
            self.col += 1
        return self.v[self.row][self.col]

    def hasNext(self):
        """:rtype: bool"""
        if self.row == 1:
            if self.col + 1 < self.n[0]:
                row_next = 0
                col_next = self.col + 1
            else:
                row_next = 1
                col_next = self.col + 1
        elif self.col < self.n[1]:
            row_next = 1
            col_next = self.col
        else:
            row_next = 0
            col_next = self.col + 1
        return col_next < self.n[row_next]


Prompt:
Implement the Python class `NetworkVisualizer` described below.

Class description:
This class is a network visualizer

Method signatures and docstrings:
- def __init__(self, weights_name_dir, hierarchy_mapping_name, gpu_num=0): This function initializes network visualizer :param weights_name_dir: the path for the weights :param hierarchy_mapping_name: the path for the hierarchy mapping :param gpu_num: 0 (default)
- def get_model(self, number_of_classes, weight_path): This function loads the model :param weight_path: model weights path :type number_of_classes: number of classes :return: model
- def visualize_conv_layers(self, layer_name='conv1', savefig_path=''): Each conv layer has several learned 'template matching' filters that maximize their output when a similar template pattern is found in the input image
- def visualize_dense_layers(self, last_layer='fc', savefig_path='', nof_times=3, class_number=20): Generate an input image that maximizes the final Dense layer output corresponding to some class class. :param last_layer: last layer name :param savefig_path: where to save the figure :param class_number: which class number do we want to check (for example class number 30 is some predicate) :param nof_times: how many times do you want to check the class :return:
- def visualize_heat_maps(self, image_paths, last_layer='fc', savefig_path=''): compute the gradient of output category with respect to input image. This should tell us how output category value changes with respect to a small change in input image pixels. :param image_paths: a list of images which we want check. for example: image_paths = ["https://www.kshs.org/cool2/graphics/dumbbell1lg.jpg", "http://tampaspeedboatadventures.com/wp-content/uploads/2010/10/DSC07011.jpg", "http://ichef-1.bbci.co.uk/news/660/cpsprodpb/1C24/production/_85540270_85540265.jpg"] :param last_layer: last layer name :param savefig_path: where to save the figure :return:

Implement the Python class `NetworkVisualizer` described below.

Class description:
This class is a network visualizer

Method signatures and docstrings:
- def __init__(self, weights_name_dir, hierarchy_mapping_name, gpu_num=0): This function initializes network visualizer :param weights_name_dir: the path for the weights :param hierarchy_mapping_name: the path for the hierarchy mapping :param gpu_num: 0 (default)
- def get_model(self, number_of_classes, weight_path): This function loads the model :param weight_path: model weights path :type number_of_classes: number of classes :return: model
- def visualize_conv_layers(self, layer_name='conv1', savefig_path=''): Each conv layer has several learned 'template matching' filters that maximize their output when a similar template pattern is found in the input image
- def visualize_dense_layers(self, last_layer='fc', savefig_path='', nof_times=3, class_number=20): Generate an input image that maximizes the final Dense layer output corresponding to some class class. :param last_layer: last layer name :param savefig_path: where to save the figure :param class_number: which class number do we want to check (for example class number 30 is some predicate) :param nof_times: how many times do you want to check the class :return:
- def visualize_heat_maps(self, image_paths, last_layer='fc', savefig_path=''): compute the gradient of output category with respect to input image. This should tell us how output category value changes with respect to a small change in input image pixels. :param image_paths: a list of images which we want check. for example: image_paths = ["https://www.kshs.org/cool2/graphics/dumbbell1lg.jpg", "http://tampaspeedboatadventures.com/wp-content/uploads/2010/10/DSC07011.jpg", "http://ichef-1.bbci.co.uk/news/660/cpsprodpb/1C24/production/_85540270_85540265.jpg"] :param last_layer: last layer name :param savefig_path: where to save the figure :return:

<|skeleton|>
class NetworkVisualizer:
    """This class is a network visualizer"""

    def __init__(self, weights_name_dir, hierarchy_mapping_name, gpu_num=0):
        """This function initializes network visualizer :param weights_name_dir: the path for the weights :param hierarchy_mapping_name: the path for the hierarchy mapping :param gpu_num: 0 (default)"""
        <|body_0|>

    def get_model(self, number_of_classes, weight_path):
        """This function loads the model :param weight_path: model weights path :type number_of_classes: number of classes :return: model"""
        <|body_1|>

    def visualize_conv_layers(self, layer_name='conv1', savefig_path=''):
        """Each conv layer has several learned 'template matching' filters that maximize their output when a similar template pattern is found in the input image"""
        <|body_2|>

    def visualize_dense_layers(self, last_layer='fc', savefig_path='', nof_times=3, class_number=20):
        """Generate an input image that maximizes the final Dense layer output corresponding to some class class. :param last_layer: last layer name :param savefig_path: where to save the figure :param class_number: which class number do we want to check (for example class number 30 is some predicate) :param nof_times: how many times do you want to check the class :return:"""
        <|body_3|>

    def visualize_heat_maps(self, image_paths, last_layer='fc', savefig_path=''):
        """compute the gradient of output category with respect to input image. This should tell us how output category value changes with respect to a small change in input image pixels. :param image_paths: a list of images which we want check. for example: image_paths = ["https://www.kshs.org/cool2/graphics/dumbbell1lg.jpg", "http://tampaspeedboatadventures.com/wp-content/uploads/2010/10/DSC07011.jpg", "http://ichef-1.bbci.co.uk/news/660/cpsprodpb/1C24/production/_85540270_85540265.jpg"] :param last_layer: last layer name :param savefig_path: where to save the figure :return:"""
        <|body_4|>

<|end_skeleton|>

<|body_start_0|>
        hierarchy_mapping_name = os.path.join('..', VG_VisualModule_PICKLES_PATH, hierarchy_mapping_name)
        model_path = os.path.join('..', weights_name_dir, WEIGHTS_NAME)
        if not os.path.exists(model_path) or not os.path.exists(hierarchy_mapping_name):
            print('Error: No Weights have been found or No Hierarchy Mapping has been found in {0} or {1}'.format(model_path, hierarchy_mapping_name))
            raise Exception
        self.hierarchy_mapping_objects = cPickle.load(open(hierarchy_mapping_name))
        self.nof_classes = len(self.hierarchy_mapping_objects)
        self.config = Config(gpu_num)
        self.model = self.get_model(self.nof_classes, weight_path=model_path)
<|end_body_0|>

<|body_start_1|>
        if K.image_dim_ordering() == 'th':
            input_shape_img = (3, None, None)
        else:
            input_shape_img = (self.config.crop_height, self.config.crop_width, 3)
        img_input = Input(shape=input_shape_img, name='image_input')
        net = ModelZoo()
        model_resnet50 = net.resnet50_base(img_input, trainable=True)
        model_resnet50 = GlobalAveragePooling2D(name='global_avg_pool')(model_resnet50)
        output_resnet50 = Dense(number_of_classes, kernel_initializer='he_normal', activation='softmax', name='fc')(model_resnet50)
        model = Model(inputs=img_input, outputs=output_resnet50, name='resnet50')
        model.summary()
        try:
            print('Start loading Weights')
            model.load_weights(weight_path, by_name=True)
            print('Finished successfully loading weights from {}'.format(weight_path))
        except Exception as e:
            print('Could not load pretrained model weights. Weights can be found at {} and {}'.format('https://github.com/fchollet/deep-learning-models/releases/download/v0.2/resnet50_weights_th_dim_ordering_th_kernels_notop.h5', 'https://github.com/fchollet/deep-learning-models/releases/download/v0.2/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5'))
            raise Exception(e)
        print('Finished successfully loading Model')
        return model
<|end_body_1|>

<|body_start_2|>
        layer_idx = [idx for idx, layer in enumerate(self.model.layers) if layer.name == layer_name][0]
        filters = np.arange(get_num_filters(self.model.layers[layer_idx]))
        vis_images = []
        for idx in filters:
            img = visualize_activation(self.model, layer_idx, filter_indices=idx)
            img = utils.draw_text(img, str(idx))
            vis_images.append(img)
        stitched = utils.stitch_images(vis_images, cols=8)
        plt.axis('off')
        plt.imshow(stitched)
        plt.title(layer_name)
        plt.savefig(savefig_path)
        print('debug')
<|end_body_2|>

<|body_start_3|>
        layer_idx = [idx for idx, layer in enumerate(self.model.layers) if layer.name == last_layer][0]
        vis_images = []
        for idx in [class_number] * nof_times:
            img = visualize_activation(self.model, layer_idx, filter_indices=idx, max_iter=500)
            img = utils.draw_text(img, str(idx))
            vis_images.append(img)
        stitched = utils.stitch_images(vis_images)
        plt.axis('off')
        plt.imshow(stitched)
        plt.title(last_layer)
        plt.savefig(savefig_path)
        print('debug')
<|end_body_3|>

<|body_start_4|>
        layer_idx = [idx for idx, layer in enumerate(self.model.layers) if layer.name == last_layer][0]
        heatmaps = []
        for path in image_paths:
            seed_img = utils.load_img(path, target_size=(self.config.crop_height, self.config.crop_width))
            x = np.expand_dims(img_to_array(seed_img), axis=0)
            x = preprocess_input(x)
            pred_class = np.argmax(self.model.predict(x))
            heatmap = visualize_saliency(self.model, layer_idx, [pred_class], seed_img)
            heatmaps.append(heatmap)
        plt.axis('off')
        plt.imshow(utils.stitch_images(heatmaps))
        plt.title('Saliency map')
        plt.savefig(savefig_path)
        print('debug')
<|end_body_4|>

Solution:
class NetworkVisualizer:
    """This class is a network visualizer"""

    def __init__(self, weights_name_dir, hierarchy_mapping_name, gpu_num=0):
        """This function initializes network visualizer :param weights_name_dir: the path for the weights :param hierarchy_mapping_name: the path for the hierarchy mapping :param gpu_num: 0 (default)"""
        hierarchy_mapping_name = os.path.join('..', VG_VisualModule_PICKLES_PATH, hierarchy_mapping_name)
        model_path = os.path.join('..', weights_name_dir, WEIGHTS_NAME)
        if not os.path.exists(model_path) or not os.path.exists(hierarchy_mapping_name):
            print('Error: No Weights have been found or No Hierarchy Mapping has been found in {0} or {1}'.format(model_path, hierarchy_mapping_name))
            raise Exception
        self.hierarchy_mapping_objects = cPickle.load(open(hierarchy_mapping_name))
        self.nof_classes = len(self.hierarchy_mapping_objects)
        self.config = Config(gpu_num)
        self.model = self.get_model(self.nof_classes, weight_path=model_path)

    def get_model(self, number_of_classes, weight_path):
        """This function loads the model :param weight_path: model weights path :type number_of_classes: number of classes :return: model"""
        if K.image_dim_ordering() == 'th':
            input_shape_img = (3, None, None)
        else:
            input_shape_img = (self.config.crop_height, self.config.crop_width, 3)
        img_input = Input(shape=input_shape_img, name='image_input')
        net = ModelZoo()
        model_resnet50 = net.resnet50_base(img_input, trainable=True)
        model_resnet50 = GlobalAveragePooling2D(name='global_avg_pool')(model_resnet50)
        output_resnet50 = Dense(number_of_classes, kernel_initializer='he_normal', activation='softmax', name='fc')(model_resnet50)
        model = Model(inputs=img_input, outputs=output_resnet50, name='resnet50')
        model.summary()
        try:
            print('Start loading Weights')
            model.load_weights(weight_path, by_name=True)
            print('Finished successfully loading weights from {}'.format(weight_path))
        except Exception as e:
            print('Could not load pretrained model weights. Weights can be found at {} and {}'.format('https://github.com/fchollet/deep-learning-models/releases/download/v0.2/resnet50_weights_th_dim_ordering_th_kernels_notop.h5', 'https://github.com/fchollet/deep-learning-models/releases/download/v0.2/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5'))
            raise Exception(e)
        print('Finished successfully loading Model')
        return model

    def visualize_conv_layers(self, layer_name='conv1', savefig_path=''):
        """Each conv layer has several learned 'template matching' filters that maximize their output when a similar template pattern is found in the input image"""
        layer_idx = [idx for idx, layer in enumerate(self.model.layers) if layer.name == layer_name][0]
        filters = np.arange(get_num_filters(self.model.layers[layer_idx]))
        vis_images = []
        for idx in filters:
            img = visualize_activation(self.model, layer_idx, filter_indices=idx)
            img = utils.draw_text(img, str(idx))
            vis_images.append(img)
        stitched = utils.stitch_images(vis_images, cols=8)
        plt.axis('off')
        plt.imshow(stitched)
        plt.title(layer_name)
        plt.savefig(savefig_path)
        print('debug')

    def visualize_dense_layers(self, last_layer='fc', savefig_path='', nof_times=3, class_number=20):
        """Generate an input image that maximizes the final Dense layer output corresponding to some class class. :param last_layer: last layer name :param savefig_path: where to save the figure :param class_number: which class number do we want to check (for example class number 30 is some predicate) :param nof_times: how many times do you want to check the class :return:"""
        layer_idx = [idx for idx, layer in enumerate(self.model.layers) if layer.name == last_layer][0]
        vis_images = []
        for idx in [class_number] * nof_times:
            img = visualize_activation(self.model, layer_idx, filter_indices=idx, max_iter=500)
            img = utils.draw_text(img, str(idx))
            vis_images.append(img)
        stitched = utils.stitch_images(vis_images)
        plt.axis('off')
        plt.imshow(stitched)
        plt.title(last_layer)
        plt.savefig(savefig_path)
        print('debug')

    def visualize_heat_maps(self, image_paths, last_layer='fc', savefig_path=''):
        """compute the gradient of output category with respect to input image. This should tell us how output category value changes with respect to a small change in input image pixels. :param image_paths: a list of images which we want check. for example: image_paths = ["https://www.kshs.org/cool2/graphics/dumbbell1lg.jpg", "http://tampaspeedboatadventures.com/wp-content/uploads/2010/10/DSC07011.jpg", "http://ichef-1.bbci.co.uk/news/660/cpsprodpb/1C24/production/_85540270_85540265.jpg"] :param last_layer: last layer name :param savefig_path: where to save the figure :return:"""
        layer_idx = [idx for idx, layer in enumerate(self.model.layers) if layer.name == last_layer][0]
        heatmaps = []
        for path in image_paths:
            seed_img = utils.load_img(path, target_size=(self.config.crop_height, self.config.crop_width))
            x = np.expand_dims(img_to_array(seed_img), axis=0)
            x = preprocess_input(x)
            pred_class = np.argmax(self.model.predict(x))
            heatmap = visualize_saliency(self.model, layer_idx, [pred_class], seed_img)
            heatmaps.append(heatmap)
        plt.axis('off')
        plt.imshow(utils.stitch_images(heatmaps))
        plt.title('Saliency map')
        plt.savefig(savefig_path)
        print('debug')


Prompt:
Implement the Python class `LineageFilter` described below.

Class description:
A filter used in a lineage query.

Method signatures and docstrings:
- def __init__(self, entities: Optional[List[Union[LineageEntityEnum, str]]]=None, sources: Optional[List[Union[LineageSourceEnum, str]]]=None, created_before: Optional[datetime]=None, created_after: Optional[datetime]=None, modified_before: Optional[datetime]=None, modified_after: Optional[datetime]=None, properties: Optional[Dict[str, str]]=None): Initialize ``LineageFilter`` instance.
- def _to_request_dict(self): Convert the lineage filter to its API representation.

Implement the Python class `LineageFilter` described below.

Class description:
A filter used in a lineage query.

Method signatures and docstrings:
- def __init__(self, entities: Optional[List[Union[LineageEntityEnum, str]]]=None, sources: Optional[List[Union[LineageSourceEnum, str]]]=None, created_before: Optional[datetime]=None, created_after: Optional[datetime]=None, modified_before: Optional[datetime]=None, modified_after: Optional[datetime]=None, properties: Optional[Dict[str, str]]=None): Initialize ``LineageFilter`` instance.
- def _to_request_dict(self): Convert the lineage filter to its API representation.

<|skeleton|>
class LineageFilter:
    """A filter used in a lineage query."""

    def __init__(self, entities: Optional[List[Union[LineageEntityEnum, str]]]=None, sources: Optional[List[Union[LineageSourceEnum, str]]]=None, created_before: Optional[datetime]=None, created_after: Optional[datetime]=None, modified_before: Optional[datetime]=None, modified_after: Optional[datetime]=None, properties: Optional[Dict[str, str]]=None):
        """Initialize ``LineageFilter`` instance."""
        <|body_0|>

    def _to_request_dict(self):
        """Convert the lineage filter to its API representation."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.entities = entities
        self.sources = sources
        self.created_before = created_before
        self.created_after = created_after
        self.modified_before = modified_before
        self.modified_after = modified_after
        self.properties = properties
<|end_body_0|>

<|body_start_1|>
        filter_request = {}
        if self.sources:
            filter_request['Types'] = list(map(lambda x: x.value if isinstance(x, LineageSourceEnum) else x, self.sources))
        if self.entities:
            filter_request['LineageTypes'] = list(map(lambda x: x.value if isinstance(x, LineageEntityEnum) else x, self.entities))
        if self.created_before:
            filter_request['CreatedBefore'] = self.created_before
        if self.created_after:
            filter_request['CreatedAfter'] = self.created_after
        if self.modified_before:
            filter_request['ModifiedBefore'] = self.modified_before
        if self.modified_after:
            filter_request['ModifiedAfter'] = self.modified_after
        if self.properties:
            filter_request['Properties'] = self.properties
        return filter_request
<|end_body_1|>

Solution:
class LineageFilter:
    """A filter used in a lineage query."""

    def __init__(self, entities: Optional[List[Union[LineageEntityEnum, str]]]=None, sources: Optional[List[Union[LineageSourceEnum, str]]]=None, created_before: Optional[datetime]=None, created_after: Optional[datetime]=None, modified_before: Optional[datetime]=None, modified_after: Optional[datetime]=None, properties: Optional[Dict[str, str]]=None):
        """Initialize ``LineageFilter`` instance."""
        self.entities = entities
        self.sources = sources
        self.created_before = created_before
        self.created_after = created_after
        self.modified_before = modified_before
        self.modified_after = modified_after
        self.properties = properties

    def _to_request_dict(self):
        """Convert the lineage filter to its API representation."""
        filter_request = {}
        if self.sources:
            filter_request['Types'] = list(map(lambda x: x.value if isinstance(x, LineageSourceEnum) else x, self.sources))
        if self.entities:
            filter_request['LineageTypes'] = list(map(lambda x: x.value if isinstance(x, LineageEntityEnum) else x, self.entities))
        if self.created_before:
            filter_request['CreatedBefore'] = self.created_before
        if self.created_after:
            filter_request['CreatedAfter'] = self.created_after
        if self.modified_before:
            filter_request['ModifiedBefore'] = self.modified_before
        if self.modified_after:
            filter_request['ModifiedAfter'] = self.modified_after
        if self.properties:
            filter_request['Properties'] = self.properties
        return filter_request


Prompt:
Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def minCut(self, s): :type s: str :rtype: int 666ms
- def minCut_1(self, s): :type s: str :rtype: int 326ms
- def minCut_2(self, s): :type s: str :rtype: int 38ms
- def minCut_3(self, s): :type s: str :rtype: int 242ms

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def minCut(self, s): :type s: str :rtype: int 666ms
- def minCut_1(self, s): :type s: str :rtype: int 326ms
- def minCut_2(self, s): :type s: str :rtype: int 38ms
- def minCut_3(self, s): :type s: str :rtype: int 242ms

<|skeleton|>
class Solution:

    def minCut(self, s):
        """:type s: str :rtype: int 666ms"""
        <|body_0|>

    def minCut_1(self, s):
        """:type s: str :rtype: int 326ms"""
        <|body_1|>

    def minCut_2(self, s):
        """:type s: str :rtype: int 38ms"""
        <|body_2|>

    def minCut_3(self, s):
        """:type s: str :rtype: int 242ms"""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        l = len(s)
        dp_is_palindrome = [[False] * l for _ in range(l)]
        dp_is_palindrome[0][0] = True
        for i in range(l):
            dp_is_palindrome[i][i] = True
            if s[i] == s[i - 1]:
                dp_is_palindrome[i - 1][i] = True
        for j in range(2, l):
            for i in range(0, j - 1):
                if s[i] == s[j] and dp_is_palindrome[i + 1][j - 1]:
                    dp_is_palindrome[i][j] = True
        print(np.array(dp_is_palindrome))
        dp = [l] * (l + 1)
        dp[0] = -1
        for i in range(l):
            for j in range(i + 1):
                if dp_is_palindrome[j][i]:
                    b = dp[j] + 1
                    dp[i + 1] = min(dp[i + 1], b)
        print(dp)
        return dp[-1]
<|end_body_0|>

<|body_start_1|>
        size = len(s)
        cut = range(-1, size)
        for idx in range(1, size):
            for low, high in ((idx, idx), (idx - 1, idx)):
                while low >= 0 and high < size and (s[low] == s[high]):
                    cut[high + 1] = min(cut[high + 1], cut[low] + 1)
                    low -= 1
                    high += 1
        return cut[-1]
<|end_body_1|>

<|body_start_2|>
        if s == s[::-1]:
            return 0
        for i in range(1, len(s)):
            if s[:i] == s[:i][::-1] and s[i:] == s[i:][::-1]:
                return 1
        cut = [x for x in range(-1, len(s))]
        for i in range(len(s)):
            r1, r2 = (0, 0)
            while i - r1 >= 0 and i + r1 < len(s) and (s[i - r1] == s[i + r1]):
                cut[i + r1 + 1] = min(cut[i + r1 + 1], cut[i - r1] + 1)
                r1 += 1
            while i - r2 >= 0 and i + r2 + 1 < len(s) and (s[i - r2] == s[i + r2 + 1]):
                cut[i + r2 + 2] = min(cut[i + r2 + 2], cut[i - r2] + 1)
                r2 += 1
        return cut[-1]
<|end_body_2|>

<|body_start_3|>
        if s == s[::-1]:
            return 0
        for i in range(1, len(s)):
            if s[:i] == s[:i][::-1] and s[i:] == s[i:][::-1]:
                return 1
        cut = [x for x in range(-1, len(s))]
        for i in range(len(s)):
            for j in range(i, len(s)):
                if s[i:j + 1] == s[i:j + 1][::-1]:
                    cut[j + 1] = min(cut[j + 1], cut[i] + 1)
        return cut[-1]
<|end_body_3|>

Solution:
class Solution:
    def minCut(self, s):
        """:type s: str :rtype: int 666ms"""
        l = len(s)
        dp_is_palindrome = [[False] * l for _ in range(l)]
        dp_is_palindrome[0][0] = True
        for i in range(l):
            dp_is_palindrome[i][i] = True
            if s[i] == s[i - 1]:
                dp_is_palindrome[i - 1][i] = True
        for j in range(2, l):
            for i in range(0, j - 1):
                if s[i] == s[j] and dp_is_palindrome[i + 1][j - 1]:
                    dp_is_palindrome[i][j] = True
        print(np.array(dp_is_palindrome))
        dp = [l] * (l + 1)
        dp[0] = -1
        for i in range(l):
            for j in range(i + 1):
                if dp_is_palindrome[j][i]:
                    b = dp[j] + 1
                    dp[i + 1] = min(dp[i + 1], b)
        print(dp)
        return dp[-1]

    def minCut_1(self, s):
        """:type s: str :rtype: int 326ms"""
        size = len(s)
        cut = range(-1, size)
        for idx in range(1, size):
            for low, high in ((idx, idx), (idx - 1, idx)):
                while low >= 0 and high < size and (s[low] == s[high]):
                    cut[high + 1] = min(cut[high + 1], cut[low] + 1)
                    low -= 1
                    high += 1
        return cut[-1]

    def minCut_2(self, s):
        """:type s: str :rtype: int 38ms"""
        if s == s[::-1]:
            return 0
        for i in range(1, len(s)):
            if s[:i] == s[:i][::-1] and s[i:] == s[i:][::-1]:
                return 1
        cut = [x for x in range(-1, len(s))]
        for i in range(len(s)):
            r1, r2 = (0, 0)
            while i - r1 >= 0 and i + r1 < len(s) and (s[i - r1] == s[i + r1]):
                cut[i + r1 + 1] = min(cut[i + r1 + 1], cut[i - r1] + 1)
                r1 += 1
            while i - r2 >= 0 and i + r2 + 1 < len(s) and (s[i - r2] == s[i + r2 + 1]):
                cut[i + r2 + 2] = min(cut[i + r2 + 2], cut[i - r2] + 1)
                r2 += 1
        return cut[-1]

    def minCut_3(self, s):
        """:type s: str :rtype: int 242ms"""
        if s == s[::-1]:
            return 0
        for i in range(1, len(s)):
            if s[:i] == s[:i][::-1] and s[i:] == s[i:][::-1]:
                return 1
        cut = [x for x in range(-1, len(s))]
        for i in range(len(s)):
            for j in range(i, len(s)):
                if s[i:j + 1] == s[i:j + 1][::-1]:
                    cut[j + 1] = min(cut[j + 1], cut[i] + 1)
        return cut[-1]


Prompt:
Implement the Python class `SuperDevice` described below.

Class description:
Implement the SuperDevice class.

Method signatures and docstrings:
- def _setup(self): Pre-connection setup.
- def _connected(self): Post-connection setup.

Implement the Python class `SuperDevice` described below.

Class description:
Implement the SuperDevice class.

Method signatures and docstrings:
- def _setup(self): Pre-connection setup.
- def _connected(self): Post-connection setup.

<|skeleton|>
class SuperDevice:

    def _setup(self):
        """Pre-connection setup."""
        <|body_0|>

    def _connected(self):
        """Post-connection setup."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.name = self.__class__.__name__
        self.resources = {}
        self.subdevices = {}
<|end_body_0|>

<|body_start_1|>
        if hasattr(self, 'driver') and self.driver == drivers.lgpib:
            if hasattr(self, 'eos_char'):
                self.device.config(gpib.IbcEOSchar, ord(self.eos_char))
                self.device.config(gpib.IbcEOSrd, 1)
            try:
                log.debug('GPIB device IDN: {0!r}'.format(self.idn))
            except gpib.GpibError as e:
                raise DeviceNotFoundError('Could not open device at "{0}".'.format(self.connection_resource), e)
        elif str(self) == '<IPS120_10>':
            self.device.read_termination = u'\r'
        for name, subdev in self.subdevices.items():
            log.debug('Post-connection for subdevice "{0}".'.format(name))
            subdev._connected()
<|end_body_1|>

Solution:
class SuperDevice:
    def _setup(self):
        """Pre-connection setup."""
        self.name = self.__class__.__name__
        self.resources = {}
        self.subdevices = {}

    def _connected(self):
        """Post-connection setup."""
        if hasattr(self, 'driver') and self.driver == drivers.lgpib:
            if hasattr(self, 'eos_char'):
                self.device.config(gpib.IbcEOSchar, ord(self.eos_char))
                self.device.config(gpib.IbcEOSrd, 1)
            try:
                log.debug('GPIB device IDN: {0!r}'.format(self.idn))
            except gpib.GpibError as e:
                raise DeviceNotFoundError('Could not open device at "{0}".'.format(self.connection_resource), e)
        elif str(self) == '<IPS120_10>':
            self.device.read_termination = u'\r'
        for name, subdev in self.subdevices.items():
            log.debug('Post-connection for subdevice "{0}".'.format(name))
            subdev._connected()


Prompt:
Implement the Python class `ManageCMFContent` described below.

Class description:
A suite of methods deploying CMF site

Method signatures and docstrings:
- def __init__(self, stream=None): Stream is expected to be some writable file object, like a StringIO, that output will be sent to
- def deploy_class(self, target, type_name, fti): Register a new type
- def register_view(self, target, view): Register a directory view
- def set_skin(self, target, views, skin_name='Site', skin_path='custom, topic, content, generic, control, Images'): Create a new skin

Implement the Python class `ManageCMFContent` described below.

Class description:
A suite of methods deploying CMF site

Method signatures and docstrings:
- def __init__(self, stream=None): Stream is expected to be some writable file object, like a StringIO, that output will be sent to
- def deploy_class(self, target, type_name, fti): Register a new type
- def register_view(self, target, view): Register a directory view
- def set_skin(self, target, views, skin_name='Site', skin_path='custom, topic, content, generic, control, Images'): Create a new skin

<|skeleton|>
class ManageCMFContent:
    """A suite of methods deploying CMF site"""

    def __init__(self, stream=None):
        """Stream is expected to be some writable file object, like a StringIO, that output will be sent to"""
        <|body_0|>

    def deploy_class(self, target, type_name, fti):
        """Register a new type"""
        <|body_1|>

    def register_view(self, target, view):
        """Register a directory view"""
        <|body_2|>

    def set_skin(self, target, views, skin_name='Site', skin_path='custom, topic, content, generic, control, Images'):
        """Create a new skin"""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        if stream is not None:
            self.stream = stream
        else:
            self.stream = StringIO()
<|end_body_0|>

<|body_start_1|>
        write = self.stream.write
        tptypes = getToolByName(target, 'portal_types', None)
        if tptypes is None:
            write('No portal_skins')
        elif not tptypes.getTypeInfo(type_name):
            tptypes.addType(type_name, fti[0])
            write('Added type object for %s \n' % type_name)
        else:
            write('Skipping type object for %s (already exists) \n' % type_name)
<|end_body_1|>

<|body_start_2|>
        skins = getToolByName(target, 'portal_skins', None)
        write = self.stream.write
        if skins._getOb(view, None) is not None:
            write("Failed to register view '%s' (already exists)\n" % view)
            return view
        found = 0
        dw_path = os.path.join(minimalpath(package_home(globals())), *view.split('/'))
        dw_path = re.sub('\\\\', '/', dw_path)
        for dir_path in DirectoryView.manage_listAvailableDirectories():
            if dir_path.endswith(dw_path):
                found = 1
                break
        if not found:
            write("Failed to register view '%s' (directory not found)\n" % view)
            return view
        dw_path = dw_path.replace('\\', '/')
        DirectoryView.manage_addDirectoryView(skins, dw_path)
        write("Registered view '%s' = '%s'\n" % (view, dw_path))
        return view
<|end_body_2|>

<|body_start_3|>
        self.skin_name = skin_name
        self.skin_path = skin_path
        skins = getToolByName(target, 'portal_skins', None)
        if skins is None:
            return
        skin_paths = skins.getSkinPaths()
        include = ()
        found = 0
        for id, path in skin_paths:
            if id == self.skin_name:
                paths = path.split(', ')
                include = filter(lambda x, cp=paths: x not in cp, views) + paths
                found = 1
        if not found:
            default_path = self.skin_path.split(', ')
            include = views + default_path
        skins.manage_properties(add_skin=1, skinname=self.skin_name, skinpath=join(include, ', '))
        skins.default_skin = self.skin_name
<|end_body_3|>

Solution:
class ManageCMFContent:
    """A suite of methods deploying CMF site"""

    def __init__(self, stream=None):
        """Stream is expected to be some writable file object, like a StringIO, that output will be sent to"""
        if stream is not None:
            self.stream = stream
        else:
            self.stream = StringIO()

    def deploy_class(self, target, type_name, fti):
        """Register a new type"""
        write = self.stream.write
        tptypes = getToolByName(target, 'portal_types', None)
        if tptypes is None:
            write('No portal_skins')
        elif not tptypes.getTypeInfo(type_name):
            tptypes.addType(type_name, fti[0])
            write('Added type object for %s \n' % type_name)
        else:
            write('Skipping type object for %s (already exists) \n' % type_name)

    def register_view(self, target, view):
        """Register a directory view"""
        skins = getToolByName(target, 'portal_skins', None)
        write = self.stream.write
        if skins._getOb(view, None) is not None:
            write("Failed to register view '%s' (already exists)\n" % view)
            return view
        found = 0
        dw_path = os.path.join(minimalpath(package_home(globals())), *view.split('/'))
        dw_path = re.sub('\\\\', '/', dw_path)
        for dir_path in DirectoryView.manage_listAvailableDirectories():
            if dir_path.endswith(dw_path):
                found = 1
                break
        if not found:
            write("Failed to register view '%s' (directory not found)\n" % view)
            return view
        dw_path = dw_path.replace('\\', '/')
        DirectoryView.manage_addDirectoryView(skins, dw_path)
        write("Registered view '%s' = '%s'\n" % (view, dw_path))
        return view

    def set_skin(self, target, views, skin_name='Site', skin_path='custom, topic, content, generic, control, Images'):
        """Create a new skin"""
        self.skin_name = skin_name
        self.skin_path = skin_path
        skins = getToolByName(target, 'portal_skins', None)
        if skins is None:
            return
        skin_paths = skins.getSkinPaths()
        include = ()
        found = 0
        for id, path in skin_paths:
            if id == self.skin_name:
                paths = path.split(', ')
                include = filter(lambda x, cp=paths: x not in cp, views) + paths
                found = 1
        if not found:
            default_path = self.skin_path.split(', ')
            include = views + default_path
        skins.manage_properties(add_skin=1, skinname=self.skin_name, skinpath=join(include, ', '))
        skins.default_skin = self.skin_name


Prompt:
Implement the Python class `KeywordsExtractionView` described below.

Class description:
Implement the KeywordsExtractionView class.

Method signatures and docstrings:
- def post(self, request): Handle API POST request
- def _validate_keywords_extraction_params(self, queryparams): Validator for params

Implement the Python class `KeywordsExtractionView` described below.

Class description:
Implement the KeywordsExtractionView class.

Method signatures and docstrings:
- def post(self, request): Handle API POST request
- def _validate_keywords_extraction_params(self, queryparams): Validator for params

<|skeleton|>
class KeywordsExtractionView:

    def post(self, request):
        """Handle API POST request"""
        <|body_0|>

    def _validate_keywords_extraction_params(self, queryparams):
        """Validator for params"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        validation_details = self._validate_keywords_extraction_params(request.data)
        if not validation_details['status']:
            return Response(validation_details['error_data'], status=status.HTTP_400_BAD_REQUEST)
        params = validation_details['params']
        doc = params['document']
        args = (doc, params['max_grams']) if params['max_grams'] else (doc,)
        key_ngrams = get_key_ngrams(*args, include_numbers=params.get('include_numbers', False))
        return Response(key_ngrams)
<|end_body_0|>

<|body_start_1|>
        errors = {}
        params = {}
        if not queryparams.get('document'):
            errors['document'] = 'document should be present'
        else:
            params['document'] = queryparams['document']
        if queryparams.get('max_grams'):
            try:
                params['max_grams'] = int(queryparams['max_grams'])
                if params['max_grams'] < 1:
                    raise Exception
            except Exception as e:
                errors['max_grams'] = 'max_grams, if present, should be a positive integer'
        else:
            params['max_grams'] = None
        inc_numbers = queryparams.get('include_numbers')
        if inc_numbers and (inc_numbers == 'true' or inc_numbers == '1'):
            params['include_numbers'] = True
        if errors:
            return {'status': False, 'error_data': errors}
        return {'status': True, 'params': params}
<|end_body_1|>

Solution:
class KeywordsExtractionView:
    def post(self, request):
        """Handle API POST request"""
        validation_details = self._validate_keywords_extraction_params(request.data)
        if not validation_details['status']:
            return Response(validation_details['error_data'], status=status.HTTP_400_BAD_REQUEST)
        params = validation_details['params']
        doc = params['document']
        args = (doc, params['max_grams']) if params['max_grams'] else (doc,)
        key_ngrams = get_key_ngrams(*args, include_numbers=params.get('include_numbers', False))
        return Response(key_ngrams)

    def _validate_keywords_extraction_params(self, queryparams):
        """Validator for params"""
        errors = {}
        params = {}
        if not queryparams.get('document'):
            errors['document'] = 'document should be present'
        else:
            params['document'] = queryparams['document']
        if queryparams.get('max_grams'):
            try:
                params['max_grams'] = int(queryparams['max_grams'])
                if params['max_grams'] < 1:
                    raise Exception
            except Exception as e:
                errors['max_grams'] = 'max_grams, if present, should be a positive integer'
        else:
            params['max_grams'] = None
        inc_numbers = queryparams.get('include_numbers')
        if inc_numbers and (inc_numbers == 'true' or inc_numbers == '1'):
            params['include_numbers'] = True
        if errors:
            return {'status': False, 'error_data': errors}
        return {'status': True, 'params': params}


write

Prompt:
Implement the Python class `Class` described below.

Class description:
Class structure. .. py:attribute:: name .. py:attribute:: classID

Method signatures and docstrings:
- def read(cls, fp): Read the element from a file-like object. :param fp: file-like object
- def write(self, fp): Write the element to a file-like object. :param fp: file-like object

Implement the Python class `Class` described below.

Class description:
Class structure. .. py:attribute:: name .. py:attribute:: classID

Method signatures and docstrings:
- def read(cls, fp): Read the element from a file-like object. :param fp: file-like object
- def write(self, fp): Write the element to a file-like object. :param fp: file-like object

<|skeleton|>
class Class:
    """Class structure. .. py:attribute:: name .. py:attribute:: classID"""

    def read(cls, fp):
        """Read the element from a file-like object. :param fp: file-like object"""
        <|body_0|>

    def write(self, fp):
        """Write the element to a file-like object. :param fp: file-like object"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        name = read_unicode_string(fp)
        classID = read_length_and_key(fp)
        return cls(name, classID)
<|end_body_0|>

<|body_start_1|>
        written = write_unicode_string(fp, self.name)
        written += write_length_and_key(fp, self.classID)
        return written
<|end_body_1|>

Solution:
class Class:
    """Class structure. .. py:attribute:: name .. py:attribute:: classID"""

    def read(cls, fp):
        """Read the element from a file-like object. :param fp: file-like object"""
        name = read_unicode_string(fp)
        classID = read_length_and_key(fp)
        return cls(name, classID)

    def write(self, fp):
        """Write the element to a file-like object. :param fp: file-like object"""
        written = write_unicode_string(fp, self.name)
        written += write_length_and_key(fp, self.classID)
        return written


Prompt:
Implement the Python class `CommonPuddleLiquid` described below.

Class description:
Various types of liquids a puddle may have.

Method signatures and docstrings:
- def convert_to_vanilla(value: 'CommonPuddleLiquid') -> Union[PuddleLiquid, None]: convert_to_vanilla(value) Convert a value into the vanilla PuddleLiquid enum. :param value: An instance of a CommonPuddleLiquid :type value: CommonPuddleLiquid :return: The specified value translated to a PuddleLiquid or INVALID if the value could not be translated. :rtype: Union[PuddleLiquid, None]
- def convert_from_vanilla(value: PuddleLiquid) -> Union['CommonPuddleLiquid', None]: convert_from_vanilla(value) Convert a value into a CommonPuddleLiquid enum. :param value: An instance of a PuddleLiquid :type value: PuddleLiquid :return: The specified value translated to a CommonPuddleLiquid or INVALID if the value could not be translated. :rtype: Union['CommonPuddleLiquid', None]

Implement the Python class `CommonPuddleLiquid` described below.

Class description:
Various types of liquids a puddle may have.

Method signatures and docstrings:
- def convert_to_vanilla(value: 'CommonPuddleLiquid') -> Union[PuddleLiquid, None]: convert_to_vanilla(value) Convert a value into the vanilla PuddleLiquid enum. :param value: An instance of a CommonPuddleLiquid :type value: CommonPuddleLiquid :return: The specified value translated to a PuddleLiquid or INVALID if the value could not be translated. :rtype: Union[PuddleLiquid, None]
- def convert_from_vanilla(value: PuddleLiquid) -> Union['CommonPuddleLiquid', None]: convert_from_vanilla(value) Convert a value into a CommonPuddleLiquid enum. :param value: An instance of a PuddleLiquid :type value: PuddleLiquid :return: The specified value translated to a CommonPuddleLiquid or INVALID if the value could not be translated. :rtype: Union['CommonPuddleLiquid', None]

<|skeleton|>
class CommonPuddleLiquid:
    """Various types of liquids a puddle may have."""

    def convert_to_vanilla(value: 'CommonPuddleLiquid') -> Union[PuddleLiquid, None]:
        """convert_to_vanilla(value) Convert a value into the vanilla PuddleLiquid enum. :param value: An instance of a CommonPuddleLiquid :type value: CommonPuddleLiquid :return: The specified value translated to a PuddleLiquid or INVALID if the value could not be translated. :rtype: Union[PuddleLiquid, None]"""
        <|body_0|>

    def convert_from_vanilla(value: PuddleLiquid) -> Union['CommonPuddleLiquid', None]:
        """convert_from_vanilla(value) Convert a value into a CommonPuddleLiquid enum. :param value: An instance of a PuddleLiquid :type value: PuddleLiquid :return: The specified value translated to a CommonPuddleLiquid or INVALID if the value could not be translated. :rtype: Union['CommonPuddleLiquid', None]"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        if value is None or value == CommonPuddleLiquid.INVALID:
            return PuddleLiquid.INVALID
        if isinstance(value, PuddleLiquid):
            return value
        mapping = dict()
        if hasattr(PuddleLiquid, 'WATER'):
            mapping[CommonPuddleLiquid.WATER] = PuddleLiquid.WATER
        if hasattr(PuddleLiquid, 'Dark Matter'):
            mapping[CommonPuddleLiquid.DARK_MATTER] = getattr(PuddleLiquid, 'Dark Matter')
        if hasattr(PuddleLiquid, 'GreenGoo'):
            mapping[CommonPuddleLiquid.GREEN_GOO] = PuddleLiquid.GreenGoo
        if hasattr(PuddleLiquid, 'Vomit'):
            mapping[CommonPuddleLiquid.VOMIT] = PuddleLiquid.Vomit
        if hasattr(PuddleLiquid, 'Mud'):
            mapping[CommonPuddleLiquid.MUD] = PuddleLiquid.Mud
        if hasattr(PuddleLiquid, 'Acid'):
            mapping[CommonPuddleLiquid.ACID] = PuddleLiquid.Acid
        return mapping.get(value, PuddleLiquid.INVALID)
<|end_body_0|>

<|body_start_1|>
        if value is None or value == CommonPuddleLiquid.INVALID:
            return PuddleLiquid.INVALID
        if isinstance(value, CommonPuddleLiquid):
            return value
        mapping = dict()
        if hasattr(PuddleLiquid, 'WATER'):
            mapping[PuddleLiquid.WATER] = CommonPuddleLiquid.WATER
        if hasattr(PuddleLiquid, 'Dark Matter'):
            mapping[getattr(PuddleLiquid, 'Dark Matter')] = CommonPuddleLiquid.DARK_MATTER
        if hasattr(PuddleLiquid, 'GreenGoo'):
            mapping[PuddleLiquid.GreenGoo] = CommonPuddleLiquid.GREEN_GOO
        if hasattr(PuddleLiquid, 'Vomit'):
            mapping[PuddleLiquid.Vomit] = CommonPuddleLiquid.VOMIT
        if hasattr(PuddleLiquid, 'Mud'):
            mapping[PuddleLiquid.Mud] = CommonPuddleLiquid.MUD
        if hasattr(PuddleLiquid, 'Acid'):
            mapping[PuddleLiquid.Acid] = CommonPuddleLiquid.ACID
        return mapping.get(value, PuddleLiquid.INVALID)
<|end_body_1|>

Solution:
class CommonPuddleLiquid:
    """Various types of liquids a puddle may have."""

    def convert_to_vanilla(value: 'CommonPuddleLiquid') -> Union[PuddleLiquid, None]:
        """convert_to_vanilla(value) Convert a value into the vanilla PuddleLiquid enum. :param value: An instance of a CommonPuddleLiquid :type value: CommonPuddleLiquid :return: The specified value translated to a PuddleLiquid or INVALID if the value could not be translated. :rtype: Union[PuddleLiquid, None]"""
        if value is None or value == CommonPuddleLiquid.INVALID:
            return PuddleLiquid.INVALID
        if isinstance(value, PuddleLiquid):
            return value
        mapping = dict()
        if hasattr(PuddleLiquid, 'WATER'):
            mapping[CommonPuddleLiquid.WATER] = PuddleLiquid.WATER
        if hasattr(PuddleLiquid, 'Dark Matter'):
            mapping[CommonPuddleLiquid.DARK_MATTER] = getattr(PuddleLiquid, 'Dark Matter')
        if hasattr(PuddleLiquid, 'GreenGoo'):
            mapping[CommonPuddleLiquid.GREEN_GOO] = PuddleLiquid.GreenGoo
        if hasattr(PuddleLiquid, 'Vomit'):
            mapping[CommonPuddleLiquid.VOMIT] = PuddleLiquid.Vomit
        if hasattr(PuddleLiquid, 'Mud'):
            mapping[CommonPuddleLiquid.MUD] = PuddleLiquid.Mud
        if hasattr(PuddleLiquid, 'Acid'):
            mapping[CommonPuddleLiquid.ACID] = PuddleLiquid.Acid
        return mapping.get(value, PuddleLiquid.INVALID)

    def convert_from_vanilla(value: PuddleLiquid) -> Union['CommonPuddleLiquid', None]:
        """convert_from_vanilla(value) Convert a value into a CommonPuddleLiquid enum. :param value: An instance of a PuddleLiquid :type value: PuddleLiquid :return: The specified value translated to a CommonPuddleLiquid or INVALID if the value could not be translated. :rtype: Union['CommonPuddleLiquid', None]"""
        if value is None or value == CommonPuddleLiquid.INVALID:
            return PuddleLiquid.INVALID
        if isinstance(value, CommonPuddleLiquid):
            return value
        mapping = dict()
        if hasattr(PuddleLiquid, 'WATER'):
            mapping[PuddleLiquid.WATER] = CommonPuddleLiquid.WATER
        if hasattr(PuddleLiquid, 'Dark Matter'):
            mapping[getattr(PuddleLiquid, 'Dark Matter')] = CommonPuddleLiquid.DARK_MATTER
        if hasattr(PuddleLiquid, 'GreenGoo'):
            mapping[PuddleLiquid.GreenGoo] = CommonPuddleLiquid.GREEN_GOO
        if hasattr(PuddleLiquid, 'Vomit'):
            mapping[PuddleLiquid.Vomit] = CommonPuddleLiquid.VOMIT
        if hasattr(PuddleLiquid, 'Mud'):
            mapping[PuddleLiquid.Mud] = CommonPuddleLiquid.MUD
        if hasattr(PuddleLiquid, 'Acid'):
            mapping[PuddleLiquid.Acid] = CommonPuddleLiquid.ACID
        return mapping.get(value, PuddleLiquid.INVALID)