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

Class description:
Collection of dataset generators and helper methods for developing data driven tests

Method signatures and docstrings:
- def _get_model_list(cls, get_model_list_method, model_type_name, *get_method_args, **get_method_kwargs): Gets list of all models in the environment.
- def _filter_model_list(cls, model_list, model_filter=None, filter_mode=None): Filters should be dictionaries with model attributes as keys and lists of attributes as key values. example: {"id": ["12345", "42"]} Include only those models who match at least one criteria in the model_filter dictionary. filter_mode can be 'inclusion' or 'exclusion'. inclusion mode will include models that match any attributes in the model_filter in the final model_list. exclusion mode will exclude any models that match attributes in the model-filer from the final model_list.
- def _modify_dataset_list(cls, dataset_list, max_datasets=None, randomize=False): Aggregates common modifiers for dataset lists

Implement the Python class `ModelBasedDatasetToolkit` described below.

Class description:
Collection of dataset generators and helper methods for developing data driven tests

Method signatures and docstrings:
- def _get_model_list(cls, get_model_list_method, model_type_name, *get_method_args, **get_method_kwargs): Gets list of all models in the environment.
- def _filter_model_list(cls, model_list, model_filter=None, filter_mode=None): Filters should be dictionaries with model attributes as keys and lists of attributes as key values. example: {"id": ["12345", "42"]} Include only those models who match at least one criteria in the model_filter dictionary. filter_mode can be 'inclusion' or 'exclusion'. inclusion mode will include models that match any attributes in the model_filter in the final model_list. exclusion mode will exclude any models that match attributes in the model-filer from the final model_list.
- def _modify_dataset_list(cls, dataset_list, max_datasets=None, randomize=False): Aggregates common modifiers for dataset lists

<|skeleton|>
class ModelBasedDatasetToolkit:
    """Collection of dataset generators and helper methods for developing data driven tests"""

    def _get_model_list(cls, get_model_list_method, model_type_name, *get_method_args, **get_method_kwargs):
        """Gets list of all models in the environment."""
        <|body_0|>

    def _filter_model_list(cls, model_list, model_filter=None, filter_mode=None):
        """Filters should be dictionaries with model attributes as keys and lists of attributes as key values. example: {"id": ["12345", "42"]} Include only those models who match at least one criteria in the model_filter dictionary. filter_mode can be 'inclusion' or 'exclusion'. inclusion mode will include models that match any attributes in the model_filter in the final model_list. exclusion mode will exclude any models that match attributes in the model-filer from the final model_list."""
        <|body_1|>

    def _modify_dataset_list(cls, dataset_list, max_datasets=None, randomize=False):
        """Aggregates common modifiers for dataset lists"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        resp = get_model_list_method(*get_method_args, **get_method_kwargs)
        if not resp.ok:
            raise DatasetGeneratorError('Request for list of {0} during data-driven-test setup failed with an HTTP {1} ERROR'.format(model_type_name, resp.status_code))
        if resp.entity is None:
            raise DatasetGeneratorError('Unable to deserialize list of {0} during data-driven-test setup.  API responded with an HTTP {1}'.format(model_type_name, resp.status_code))
        return resp.entity
<|end_body_0|>

<|body_start_1|>
        if not model_filter:
            return model_list
        if filter_mode not in [cls.INCLUSION_MODE, cls.EXCLUSION_MODE]:
            raise Exception("Invalid filter_mode {0}.  _filter_model_list must be called with a mode set to either 'inclusion' or 'exclusion'.".format(filter_mode))
        final_list = []
        for model in model_list:
            excluded = False
            for k in model_filter:
                if filter_mode == cls.INCLUSION_MODE:
                    if str(getattr(model, k)) in model_filter[k]:
                        final_list.append(model)
                        break
                elif filter_mode == cls.EXCLUSION_MODE:
                    model_value = str(getattr(model, k))
                    filter_value = model_filter[k]
                    if not excluded and model_value not in filter_value:
                        final_list.append(model)
                        break
                    else:
                        excluded = True
        return final_list
<|end_body_1|>

<|body_start_2|>
        if randomize:
            shuffle(dataset_list)
        if max_datasets:
            dataset_list = DatasetList(dataset_list[:max_datasets])
        return dataset_list
<|end_body_2|>

Solution:
class ModelBasedDatasetToolkit:
    """Collection of dataset generators and helper methods for developing data driven tests"""

    def _get_model_list(cls, get_model_list_method, model_type_name, *get_method_args, **get_method_kwargs):
        """Gets list of all models in the environment."""
        resp = get_model_list_method(*get_method_args, **get_method_kwargs)
        if not resp.ok:
            raise DatasetGeneratorError('Request for list of {0} during data-driven-test setup failed with an HTTP {1} ERROR'.format(model_type_name, resp.status_code))
        if resp.entity is None:
            raise DatasetGeneratorError('Unable to deserialize list of {0} during data-driven-test setup.  API responded with an HTTP {1}'.format(model_type_name, resp.status_code))
        return resp.entity

    def _filter_model_list(cls, model_list, model_filter=None, filter_mode=None):
        """Filters should be dictionaries with model attributes as keys and lists of attributes as key values. example: {"id": ["12345", "42"]} Include only those models who match at least one criteria in the model_filter dictionary. filter_mode can be 'inclusion' or 'exclusion'. inclusion mode will include models that match any attributes in the model_filter in the final model_list. exclusion mode will exclude any models that match attributes in the model-filer from the final model_list."""
        if not model_filter:
            return model_list
        if filter_mode not in [cls.INCLUSION_MODE, cls.EXCLUSION_MODE]:
            raise Exception("Invalid filter_mode {0}.  _filter_model_list must be called with a mode set to either 'inclusion' or 'exclusion'.".format(filter_mode))
        final_list = []
        for model in model_list:
            excluded = False
            for k in model_filter:
                if filter_mode == cls.INCLUSION_MODE:
                    if str(getattr(model, k)) in model_filter[k]:
                        final_list.append(model)
                        break
                elif filter_mode == cls.EXCLUSION_MODE:
                    model_value = str(getattr(model, k))
                    filter_value = model_filter[k]
                    if not excluded and model_value not in filter_value:
                        final_list.append(model)
                        break
                    else:
                        excluded = True
        return final_list

    def _modify_dataset_list(cls, dataset_list, max_datasets=None, randomize=False):
        """Aggregates common modifiers for dataset lists"""
        if randomize:
            shuffle(dataset_list)
        if max_datasets:
            dataset_list = DatasetList(dataset_list[:max_datasets])
        return dataset_list


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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def summaryRanges_group(self, nums): :type nums: List[int] :rtype: List[str]
- def summaryRanges_onepass(self, nums): :type nums: List[int] :rtype: List[str]

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def summaryRanges_group(self, nums): :type nums: List[int] :rtype: List[str]
- def summaryRanges_onepass(self, nums): :type nums: List[int] :rtype: List[str]

<|skeleton|>
class Solution:

    def summaryRanges_group(self, nums):
        """:type nums: List[int] :rtype: List[str]"""
        <|body_0|>

    def summaryRanges_onepass(self, nums):
        """:type nums: List[int] :rtype: List[str]"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        ans = []
        start = 0
        for p, group in itertools.groupby([n - v for n, v in enumerate(nums)]):
            interval = len(list(group))
            end = start + interval
            if interval == 1:
                ans.append(str(nums[start]))
            else:
                ans.append('{}->{}'.format(nums[start], nums[end - 1]))
            start = end
        return ans
<|end_body_0|>

<|body_start_1|>
        start = 0
        ans = []
        nums.append(float('INF'))
        for i in range(1, len(nums)):
            if nums[i] > nums[i - 1] + 1:
                if i - 1 == start:
                    ans.append(str(nums[start]))
                else:
                    ans.append(str(nums[start]) + '->' + str(nums[i - 1]))
                start = i
        return ans
<|end_body_1|>

Solution:
class Solution:
    def summaryRanges_group(self, nums):
        """:type nums: List[int] :rtype: List[str]"""
        ans = []
        start = 0
        for p, group in itertools.groupby([n - v for n, v in enumerate(nums)]):
            interval = len(list(group))
            end = start + interval
            if interval == 1:
                ans.append(str(nums[start]))
            else:
                ans.append('{}->{}'.format(nums[start], nums[end - 1]))
            start = end
        return ans

    def summaryRanges_onepass(self, nums):
        """:type nums: List[int] :rtype: List[str]"""
        start = 0
        ans = []
        nums.append(float('INF'))
        for i in range(1, len(nums)):
            if nums[i] > nums[i - 1] + 1:
                if i - 1 == start:
                    ans.append(str(nums[start]))
                else:
                    ans.append(str(nums[start]) + '->' + str(nums[i - 1]))
                start = i
        return ans


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

Class description:
Example of usage: with Timer("TimedFunction", newline=True, color='blue'): ... # do something

Method signatures and docstrings:
- def __init__(self, txt: str, newline: bool=False, color: str=None): Parameters ---------- txt: str Name of this timer. newline: bool Wheter you want prints to end with newlines. color: str One of 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', or 'white'.
- def __enter__(self): Used at the beginning of the section inside "With Timer()". Prints txt and starts time.
- def __exit__(self, type, value, tb): Used at the end of the section inside "With Timer()". Prints 'done' and the final time.

Implement the Python class `Timer` described below.

Class description:
Example of usage: with Timer("TimedFunction", newline=True, color='blue'): ... # do something

Method signatures and docstrings:
- def __init__(self, txt: str, newline: bool=False, color: str=None): Parameters ---------- txt: str Name of this timer. newline: bool Wheter you want prints to end with newlines. color: str One of 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', or 'white'.
- def __enter__(self): Used at the beginning of the section inside "With Timer()". Prints txt and starts time.
- def __exit__(self, type, value, tb): Used at the end of the section inside "With Timer()". Prints 'done' and the final time.

<|skeleton|>
class Timer:
    """Example of usage: with Timer("TimedFunction", newline=True, color='blue'): ... # do something"""

    def __init__(self, txt: str, newline: bool=False, color: str=None):
        """Parameters ---------- txt: str Name of this timer. newline: bool Wheter you want prints to end with newlines. color: str One of 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', or 'white'."""
        <|body_0|>

    def __enter__(self):
        """Used at the beginning of the section inside "With Timer()". Prints txt and starts time."""
        <|body_1|>

    def __exit__(self, type, value, tb):
        """Used at the end of the section inside "With Timer()". Prints 'done' and the final time."""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        try:
            prepend = COLOR_CODES[color] if color else ''
            append = COLOR_CODES['reset'] if color else ''
        except KeyError:
            prepend = ''
            append = ''
        self.txt = prepend + txt + append
        self.newline = newline
<|end_body_0|>

<|body_start_1|>
        self.start = time()
        if not self.newline:
            print(self.txt + '... ', end='')
            sys.stdout.flush()
        else:
            print(self.txt + '... ')
<|end_body_1|>

<|body_start_2|>
        if self.newline:
            print(self.txt + ' done in ', end='')
        print('{:.2f} sec.'.format(time() - self.start))
<|end_body_2|>

Solution:
class Timer:
    """Example of usage: with Timer("TimedFunction", newline=True, color='blue'): ... # do something"""

    def __init__(self, txt: str, newline: bool=False, color: str=None):
        """Parameters ---------- txt: str Name of this timer. newline: bool Wheter you want prints to end with newlines. color: str One of 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', or 'white'."""
        try:
            prepend = COLOR_CODES[color] if color else ''
            append = COLOR_CODES['reset'] if color else ''
        except KeyError:
            prepend = ''
            append = ''
        self.txt = prepend + txt + append
        self.newline = newline

    def __enter__(self):
        """Used at the beginning of the section inside "With Timer()". Prints txt and starts time."""
        self.start = time()
        if not self.newline:
            print(self.txt + '... ', end='')
            sys.stdout.flush()
        else:
            print(self.txt + '... ')

    def __exit__(self, type, value, tb):
        """Used at the end of the section inside "With Timer()". Prints 'done' and the final time."""
        if self.newline:
            print(self.txt + ' done in ', end='')
        print('{:.2f} sec.'.format(time() - self.start))


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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def canReorderDoubled(self, A): :type A: List[int] :rtype: bool 400 ms
- def canReorderDoubled_1(self, A): :type A: List[int] :rtype: bool 120ms

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def canReorderDoubled(self, A): :type A: List[int] :rtype: bool 400 ms
- def canReorderDoubled_1(self, A): :type A: List[int] :rtype: bool 120ms

<|skeleton|>
class Solution:

    def canReorderDoubled(self, A):
        """:type A: List[int] :rtype: bool 400 ms"""
        <|body_0|>

    def canReorderDoubled_1(self, A):
        """:type A: List[int] :rtype: bool 120ms"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        import collections
        A = sorted(A, key=lambda a: abs(a))
        count_A = collections.Counter(A)
        for a in A:
            if count_A[a] >= 1:
                count_A[a] -= 1
                flag = count_A.get(a * 2, 0)
                if flag >= 1:
                    count_A[a * 2] -= 1
                else:
                    return False
        return True
<|end_body_0|>

<|body_start_1|>
        from collections import defaultdict
        cts = defaultdict(int)
        for v in A:
            cts[v] += 1
        keys = cts.keys()
        for k in keys:
            if k % 2 == 1:
                if cts[2 * k] < cts[k]:
                    return False
                cts[2 * k] -= cts[k]
                del cts[k]
                if cts[2 * k] == 0:
                    del cts[2 * k]
        negs = sorted([-k for k in keys if cts[k] > 0 and k < 0])
        pos = sorted([k for k in keys if cts[k] > 0 and k > 0])
        zeros = cts[0]
        if zeros % 2 == 1:
            return False
        keys = [-k for k in negs] + pos
        for k in keys:
            if cts[k] == 0:
                continue
            if cts[2 * k] < cts[k]:
                return False
            cts[2 * k] -= cts[k]
            del cts[k]
        return True
<|end_body_1|>

Solution:
class Solution:
    def canReorderDoubled(self, A):
        """:type A: List[int] :rtype: bool 400 ms"""
        import collections
        A = sorted(A, key=lambda a: abs(a))
        count_A = collections.Counter(A)
        for a in A:
            if count_A[a] >= 1:
                count_A[a] -= 1
                flag = count_A.get(a * 2, 0)
                if flag >= 1:
                    count_A[a * 2] -= 1
                else:
                    return False
        return True

    def canReorderDoubled_1(self, A):
        """:type A: List[int] :rtype: bool 120ms"""
        from collections import defaultdict
        cts = defaultdict(int)
        for v in A:
            cts[v] += 1
        keys = cts.keys()
        for k in keys:
            if k % 2 == 1:
                if cts[2 * k] < cts[k]:
                    return False
                cts[2 * k] -= cts[k]
                del cts[k]
                if cts[2 * k] == 0:
                    del cts[2 * k]
        negs = sorted([-k for k in keys if cts[k] > 0 and k < 0])
        pos = sorted([k for k in keys if cts[k] > 0 and k > 0])
        zeros = cts[0]
        if zeros % 2 == 1:
            return False
        keys = [-k for k in negs] + pos
        for k in keys:
            if cts[k] == 0:
                continue
            if cts[2 * k] < cts[k]:
                return False
            cts[2 * k] -= cts[k]
            del cts[k]
        return True


copy

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

Class description:
Attributes ---------- buffer_type : `type<CCharArrayType>` C char array type for creating buffer. channels : `int` The number of channels. (1 if mono, 2 if stereo.) frame_length : `int` The length of a frame in milliseconds. frame_size : `int` The size of a frame in bytes. sampling_rate : `int` The number of samples per second that are taken of a waveform to create a digital signal. The higher the sample rate, the more snapshots are captured in the audio signal. sample_size : `int` The number of bits used to describe each sample. A sample is a value represented in `i16`. Each channel has their own samples. samples_per_frame : `int` The amount of samples that are in each frame.

Method signatures and docstrings:
- def __new__(cls, *, channels=..., frame_length=..., sampling_rate=...): Creates a new audio setting. Parameters ---------- channels : `int`, Optional (Keyword only) The number of channels. frame_length : `int`, Optional (Keyword only) The length of a frame in milliseconds. sampling_rate : `int`, Optional (Keyword only) The number of samples per second that are taken of a waveform to create a digital signal. Raises ------ TypeError - If a parameter's type is incorrect. ValueError - If a parameter's value is incorrect.
- def __eq__(self, other): Returns whether the two audio settings are equal.
- def __repr__(self): Returns the audio settings representation.
- def copy(self): Copies the audio settings. Returns ------- new : `instance<type<self>>`
- def copy_with(self, *, channels=..., frame_length=..., sampling_rate=...): Copies the audio settings with the given fields. Parameters ---------- channels : `int`, Optional (Keyword only) The number of channels. frame_length : `int`, Optional (Keyword only) The length of a frame in milliseconds. sampling_rate : `int`, Optional (Keyword only) The number of samples per second that are taken of a waveform to create a digital signal. Returns ------- new : `instance<type<self>>` Raises ------ TypeError - If a parameter's type is incorrect. ValueError - If a parameter's value is incorrect.

Implement the Python class `AudioSettings` described below.

Class description:
Attributes ---------- buffer_type : `type<CCharArrayType>` C char array type for creating buffer. channels : `int` The number of channels. (1 if mono, 2 if stereo.) frame_length : `int` The length of a frame in milliseconds. frame_size : `int` The size of a frame in bytes. sampling_rate : `int` The number of samples per second that are taken of a waveform to create a digital signal. The higher the sample rate, the more snapshots are captured in the audio signal. sample_size : `int` The number of bits used to describe each sample. A sample is a value represented in `i16`. Each channel has their own samples. samples_per_frame : `int` The amount of samples that are in each frame.

Method signatures and docstrings:
- def __new__(cls, *, channels=..., frame_length=..., sampling_rate=...): Creates a new audio setting. Parameters ---------- channels : `int`, Optional (Keyword only) The number of channels. frame_length : `int`, Optional (Keyword only) The length of a frame in milliseconds. sampling_rate : `int`, Optional (Keyword only) The number of samples per second that are taken of a waveform to create a digital signal. Raises ------ TypeError - If a parameter's type is incorrect. ValueError - If a parameter's value is incorrect.
- def __eq__(self, other): Returns whether the two audio settings are equal.
- def __repr__(self): Returns the audio settings representation.
- def copy(self): Copies the audio settings. Returns ------- new : `instance<type<self>>`
- def copy_with(self, *, channels=..., frame_length=..., sampling_rate=...): Copies the audio settings with the given fields. Parameters ---------- channels : `int`, Optional (Keyword only) The number of channels. frame_length : `int`, Optional (Keyword only) The length of a frame in milliseconds. sampling_rate : `int`, Optional (Keyword only) The number of samples per second that are taken of a waveform to create a digital signal. Returns ------- new : `instance<type<self>>` Raises ------ TypeError - If a parameter's type is incorrect. ValueError - If a parameter's value is incorrect.

<|skeleton|>
class AudioSettings:
    """Attributes ---------- buffer_type : `type<CCharArrayType>` C char array type for creating buffer. channels : `int` The number of channels. (1 if mono, 2 if stereo.) frame_length : `int` The length of a frame in milliseconds. frame_size : `int` The size of a frame in bytes. sampling_rate : `int` The number of samples per second that are taken of a waveform to create a digital signal. The higher the sample rate, the more snapshots are captured in the audio signal. sample_size : `int` The number of bits used to describe each sample. A sample is a value represented in `i16`. Each channel has their own samples. samples_per_frame : `int` The amount of samples that are in each frame."""

    def __new__(cls, *, channels=..., frame_length=..., sampling_rate=...):
        """Creates a new audio setting. Parameters ---------- channels : `int`, Optional (Keyword only) The number of channels. frame_length : `int`, Optional (Keyword only) The length of a frame in milliseconds. sampling_rate : `int`, Optional (Keyword only) The number of samples per second that are taken of a waveform to create a digital signal. Raises ------ TypeError - If a parameter's type is incorrect. ValueError - If a parameter's value is incorrect."""
        <|body_0|>

    def __eq__(self, other):
        """Returns whether the two audio settings are equal."""
        <|body_1|>

    def __repr__(self):
        """Returns the audio settings representation."""
        <|body_2|>

    def copy(self):
        """Copies the audio settings. Returns ------- new : `instance<type<self>>`"""
        <|body_3|>

    def copy_with(self, *, channels=..., frame_length=..., sampling_rate=...):
        """Copies the audio settings with the given fields. Parameters ---------- channels : `int`, Optional (Keyword only) The number of channels. frame_length : `int`, Optional (Keyword only) The length of a frame in milliseconds. sampling_rate : `int`, Optional (Keyword only) The number of samples per second that are taken of a waveform to create a digital signal. Returns ------- new : `instance<type<self>>` Raises ------ TypeError - If a parameter's type is incorrect. ValueError - If a parameter's value is incorrect."""
        <|body_4|>

<|end_skeleton|>

<|body_start_0|>
        if channels is ...:
            channels = CHANNELS_DEFAULT
        else:
            channels = validate_channels(channels)
        if frame_length is ...:
            frame_length = FRAME_LENGTH_DEFAULT
        else:
            frame_length = validate_frame_length(frame_length)
        if sampling_rate is ...:
            sampling_rate = SAMPLING_RATE_DEFAULT
        else:
            sampling_rate = validate_sampling_rate(sampling_rate)
        sample_size = 2 * channels
        samples_per_frame = int(sampling_rate / 1000 * frame_length)
        frame_size = samples_per_frame * sample_size
        buffer_type = CCharType * frame_size
        self = object.__new__(cls)
        self.buffer_type = buffer_type
        self.channels = channels
        self.frame_length = frame_length
        self.frame_size = frame_size
        self.samples_per_frame = samples_per_frame
        self.sampling_rate = sampling_rate
        self.sample_size = sample_size
        return self
<|end_body_0|>

<|body_start_1|>
        if type(self) is not type(other):
            return NotImplemented
        if self.channels != other.channels:
            return False
        if self.frame_length != other.frame_length:
            return False
        if self.sampling_rate != other.sampling_rate:
            return False
        return True
<|end_body_1|>

<|body_start_2|>
        repr_parts = ['<', self.__class__.__name__]
        repr_parts.append(' channels = ')
        repr_parts.append(repr(self.channels))
        repr_parts.append(', frame_length = ')
        repr_parts.append(repr(self.frame_length))
        repr_parts.append(', sampling_rate = ')
        repr_parts.append(repr(self.sampling_rate))
        repr_parts.append('>')
        return ''.join(repr_parts)
<|end_body_2|>

<|body_start_3|>
        new = object.__new__(type(self))
        new.buffer_type = self.buffer_type
        new.channels = self.channels
        new.frame_length = self.frame_length
        new.frame_size = self.frame_size
        new.samples_per_frame = self.samples_per_frame
        new.sampling_rate = self.sampling_rate
        new.sample_size = self.sample_size
        return new
<|end_body_3|>

<|body_start_4|>
        if channels is ...:
            channels = self.channels
        else:
            channels = validate_channels(channels)
        if frame_length is ...:
            frame_length = self.frame_length
        else:
            frame_length = validate_frame_length(frame_length)
        if sampling_rate is ...:
            sampling_rate = self.sampling_rate
        else:
            sampling_rate = validate_sampling_rate(sampling_rate)
        sample_size = 2 * channels
        samples_per_frame = int(sampling_rate / 1000 * frame_length)
        frame_size = samples_per_frame * sample_size
        buffer_type = CCharType * frame_size
        new = object.__new__(type(self))
        new.buffer_type = buffer_type
        new.channels = channels
        new.frame_length = frame_length
        new.frame_size = frame_size
        new.samples_per_frame = samples_per_frame
        new.sampling_rate = sampling_rate
        new.sample_size = sample_size
        return new
<|end_body_4|>

Solution:
class AudioSettings:
    """Attributes ---------- buffer_type : `type<CCharArrayType>` C char array type for creating buffer. channels : `int` The number of channels. (1 if mono, 2 if stereo.) frame_length : `int` The length of a frame in milliseconds. frame_size : `int` The size of a frame in bytes. sampling_rate : `int` The number of samples per second that are taken of a waveform to create a digital signal. The higher the sample rate, the more snapshots are captured in the audio signal. sample_size : `int` The number of bits used to describe each sample. A sample is a value represented in `i16`. Each channel has their own samples. samples_per_frame : `int` The amount of samples that are in each frame."""

    def __new__(cls, *, channels=..., frame_length=..., sampling_rate=...):
        """Creates a new audio setting. Parameters ---------- channels : `int`, Optional (Keyword only) The number of channels. frame_length : `int`, Optional (Keyword only) The length of a frame in milliseconds. sampling_rate : `int`, Optional (Keyword only) The number of samples per second that are taken of a waveform to create a digital signal. Raises ------ TypeError - If a parameter's type is incorrect. ValueError - If a parameter's value is incorrect."""
        if channels is ...:
            channels = CHANNELS_DEFAULT
        else:
            channels = validate_channels(channels)
        if frame_length is ...:
            frame_length = FRAME_LENGTH_DEFAULT
        else:
            frame_length = validate_frame_length(frame_length)
        if sampling_rate is ...:
            sampling_rate = SAMPLING_RATE_DEFAULT
        else:
            sampling_rate = validate_sampling_rate(sampling_rate)
        sample_size = 2 * channels
        samples_per_frame = int(sampling_rate / 1000 * frame_length)
        frame_size = samples_per_frame * sample_size
        buffer_type = CCharType * frame_size
        self = object.__new__(cls)
        self.buffer_type = buffer_type
        self.channels = channels
        self.frame_length = frame_length
        self.frame_size = frame_size
        self.samples_per_frame = samples_per_frame
        self.sampling_rate = sampling_rate
        self.sample_size = sample_size
        return self

    def __eq__(self, other):
        """Returns whether the two audio settings are equal."""
        if type(self) is not type(other):
            return NotImplemented
        if self.channels != other.channels:
            return False
        if self.frame_length != other.frame_length:
            return False
        if self.sampling_rate != other.sampling_rate:
            return False
        return True

    def __repr__(self):
        """Returns the audio settings representation."""
        repr_parts = ['<', self.__class__.__name__]
        repr_parts.append(' channels = ')
        repr_parts.append(repr(self.channels))
        repr_parts.append(', frame_length = ')
        repr_parts.append(repr(self.frame_length))
        repr_parts.append(', sampling_rate = ')
        repr_parts.append(repr(self.sampling_rate))
        repr_parts.append('>')
        return ''.join(repr_parts)

    def copy(self):
        """Copies the audio settings. Returns ------- new : `instance<type<self>>`"""
        new = object.__new__(type(self))
        new.buffer_type = self.buffer_type
        new.channels = self.channels
        new.frame_length = self.frame_length
        new.frame_size = self.frame_size
        new.samples_per_frame = self.samples_per_frame
        new.sampling_rate = self.sampling_rate
        new.sample_size = self.sample_size
        return new

    def copy_with(self, *, channels=..., frame_length=..., sampling_rate=...):
        """Copies the audio settings with the given fields. Parameters ---------- channels : `int`, Optional (Keyword only) The number of channels. frame_length : `int`, Optional (Keyword only) The length of a frame in milliseconds. sampling_rate : `int`, Optional (Keyword only) The number of samples per second that are taken of a waveform to create a digital signal. Returns ------- new : `instance<type<self>>` Raises ------ TypeError - If a parameter's type is incorrect. ValueError - If a parameter's value is incorrect."""
        if channels is ...:
            channels = self.channels
        else:
            channels = validate_channels(channels)
        if frame_length is ...:
            frame_length = self.frame_length
        else:
            frame_length = validate_frame_length(frame_length)
        if sampling_rate is ...:
            sampling_rate = self.sampling_rate
        else:
            sampling_rate = validate_sampling_rate(sampling_rate)
        sample_size = 2 * channels
        samples_per_frame = int(sampling_rate / 1000 * frame_length)
        frame_size = samples_per_frame * sample_size
        buffer_type = CCharType * frame_size
        new = object.__new__(type(self))
        new.buffer_type = buffer_type
        new.channels = channels
        new.frame_length = frame_length
        new.frame_size = frame_size
        new.samples_per_frame = samples_per_frame
        new.sampling_rate = sampling_rate
        new.sample_size = sample_size
        return new


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

Class description:
Implement the KthLargest class.

Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int

Implement the Python class `KthLargest` described below.

Class description:
Implement the KthLargest class.

Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int

<|skeleton|>
class KthLargest:

    def __init__(self, k, nums):
        """:type k: int :type nums: List[int]"""
        <|body_0|>

    def add(self, val):
        """:type val: int :rtype: int"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.k = k
        self.nums = nums
        heapq.heapify(self.nums)
<|end_body_0|>

<|body_start_1|>
        heapq.heappush(self.nums, val)
        while len(self.nums) > self.k:
            heapq.heappop(self.nums)
        return self.nums[0]
<|end_body_1|>

Solution:
class KthLargest:
    def __init__(self, k, nums):
        """:type k: int :type nums: List[int]"""
        self.k = k
        self.nums = nums
        heapq.heapify(self.nums)

    def add(self, val):
        """:type val: int :rtype: int"""
        heapq.heappush(self.nums, val)
        while len(self.nums) > self.k:
            heapq.heappop(self.nums)
        return self.nums[0]


encrypt

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

Class description:
The PresharedKey algorithm. Typically, you will use `PresharedKey.create_manifest(...)` to create a Manifest TLV out of a ccnpy.flic.Node.

Method signatures and docstrings:
- def __init__(self, key, key_number): :param key: A ccnpy.crypto.AesGcmKey :param key_number: An integer used to reference the key
- def encrypt(self, node): :param node: A ccnpy.flic.Node :return: (security_ctx, encrypted_node, auth_tag)
- def create_encrypted_manifest(self, node): :param node: A ccnpy.flic.Node to encrypt and wrap in a Manifest :return: A ccnpy.flic.Manifest
- def decrypt_node(self, security_ctx, encrypted_node, auth_tag): Example: manifest = ccnpy.flic.Manifest.deserialize(payload.value()) if isinstance(manifest.security_ctx(), ccnpy.flic.PresharedKeyCtx): # keystore is not necessarily provided key = keystore.get(manifest.security_ctx().key_number()) psk = ccnpy.flic.PresharedKey(key) node = psk.decrypt_node(manifest.security_ctx(), manifest.node(), manifest.auth_tag()) :param security_ctx: A ccnpy.flic.PresharedKeyCtx :param encrypted_node: A ccnpy.flic.EncryptedNode :param auth_tag: A ccnpy.flic.AuthTag :return: a ccnpy.flic.Node
- def decrypt_manifest(self, encrypted_manifest): Example: manifest = ccnpy.flic.Manifest.deserialize(payload.value()) if isinstance(manifest.security_ctx(), ccnpy.flic.PresharedKeyCtx): # keystore is not necessarily provided key = keystore.get(manifest.security_ctx().key_number()) psk = ccnpy.flic.PresharedKey(key) manifest = psk.decrypt_to_manifest(manifest) :param encrypted_manifest: :return: A decrypted manifest

Implement the Python class `PresharedKey` described below.

Class description:
The PresharedKey algorithm. Typically, you will use `PresharedKey.create_manifest(...)` to create a Manifest TLV out of a ccnpy.flic.Node.

Method signatures and docstrings:
- def __init__(self, key, key_number): :param key: A ccnpy.crypto.AesGcmKey :param key_number: An integer used to reference the key
- def encrypt(self, node): :param node: A ccnpy.flic.Node :return: (security_ctx, encrypted_node, auth_tag)
- def create_encrypted_manifest(self, node): :param node: A ccnpy.flic.Node to encrypt and wrap in a Manifest :return: A ccnpy.flic.Manifest
- def decrypt_node(self, security_ctx, encrypted_node, auth_tag): Example: manifest = ccnpy.flic.Manifest.deserialize(payload.value()) if isinstance(manifest.security_ctx(), ccnpy.flic.PresharedKeyCtx): # keystore is not necessarily provided key = keystore.get(manifest.security_ctx().key_number()) psk = ccnpy.flic.PresharedKey(key) node = psk.decrypt_node(manifest.security_ctx(), manifest.node(), manifest.auth_tag()) :param security_ctx: A ccnpy.flic.PresharedKeyCtx :param encrypted_node: A ccnpy.flic.EncryptedNode :param auth_tag: A ccnpy.flic.AuthTag :return: a ccnpy.flic.Node
- def decrypt_manifest(self, encrypted_manifest): Example: manifest = ccnpy.flic.Manifest.deserialize(payload.value()) if isinstance(manifest.security_ctx(), ccnpy.flic.PresharedKeyCtx): # keystore is not necessarily provided key = keystore.get(manifest.security_ctx().key_number()) psk = ccnpy.flic.PresharedKey(key) manifest = psk.decrypt_to_manifest(manifest) :param encrypted_manifest: :return: A decrypted manifest

<|skeleton|>
class PresharedKey:
    """The PresharedKey algorithm. Typically, you will use `PresharedKey.create_manifest(...)` to create a Manifest TLV out of a ccnpy.flic.Node."""

    def __init__(self, key, key_number):
        """:param key: A ccnpy.crypto.AesGcmKey :param key_number: An integer used to reference the key"""
        <|body_0|>

    def encrypt(self, node):
        """:param node: A ccnpy.flic.Node :return: (security_ctx, encrypted_node, auth_tag)"""
        <|body_1|>

    def create_encrypted_manifest(self, node):
        """:param node: A ccnpy.flic.Node to encrypt and wrap in a Manifest :return: A ccnpy.flic.Manifest"""
        <|body_2|>

    def decrypt_node(self, security_ctx, encrypted_node, auth_tag):
        """Example: manifest = ccnpy.flic.Manifest.deserialize(payload.value()) if isinstance(manifest.security_ctx(), ccnpy.flic.PresharedKeyCtx): # keystore is not necessarily provided key = keystore.get(manifest.security_ctx().key_number()) psk = ccnpy.flic.PresharedKey(key) node = psk.decrypt_node(manifest.security_ctx(), manifest.node(), manifest.auth_tag()) :param security_ctx: A ccnpy.flic.PresharedKeyCtx :param encrypted_node: A ccnpy.flic.EncryptedNode :param auth_tag: A ccnpy.flic.AuthTag :return: a ccnpy.flic.Node"""
        <|body_3|>

    def decrypt_manifest(self, encrypted_manifest):
        """Example: manifest = ccnpy.flic.Manifest.deserialize(payload.value()) if isinstance(manifest.security_ctx(), ccnpy.flic.PresharedKeyCtx): # keystore is not necessarily provided key = keystore.get(manifest.security_ctx().key_number()) psk = ccnpy.flic.PresharedKey(key) manifest = psk.decrypt_to_manifest(manifest) :param encrypted_manifest: :return: A decrypted manifest"""
        <|body_4|>

<|end_skeleton|>

<|body_start_0|>
        if not isinstance(key, ccnpy.crypto.AesGcmKey):
            raise TypeError('key must be ccnpy.crypto.AesGcmKey')
        self._key = key
        self._key_number = key_number
<|end_body_0|>

<|body_start_1|>
        if not isinstance(node, ccnpy.flic.Node):
            raise TypeError('node must be ccnpy.flic.Node')
        plaintext = node.serialized_value()
        iv = self._key.nonce()
        security_ctx = None
        if len(self._key) == 128:
            security_ctx = PresharedKeyCtx.create_aes_gcm_128(key_number=self._key_number, iv=iv)
        elif len(self._key) == 256:
            security_ctx = PresharedKeyCtx.create_aes_gcm_256(key_number=self._key_number, iv=iv)
        else:
            raise ValueError('Unsupported key length %r' % len(self._key))
        ciphertext, a = self._key.encrypt(nonce=iv, plaintext=plaintext, associated_data=security_ctx.serialize())
        encrypted_node = ccnpy.flic.EncryptedNode(ciphertext)
        auth_tag = ccnpy.flic.AuthTag(a)
        return (security_ctx, encrypted_node, auth_tag)
<|end_body_1|>

<|body_start_2|>
        security_ctx, encrypted_node, auth_tag = self.encrypt(node)
        manifest = ccnpy.flic.Manifest(security_ctx=security_ctx, node=encrypted_node, auth_tag=auth_tag)
        return manifest
<|end_body_2|>

<|body_start_3|>
        if not isinstance(encrypted_node, ccnpy.flic.EncryptedNode):
            raise TypeError('encrypted_node must be ccnpy.flic.EncryptedNode')
        if security_ctx is None:
            raise ValueError('security context must not be None')
        if not isinstance(security_ctx, ccnpy.flic.presharedkey.PresharedKeyCtx):
            raise TypeError('security_ctx must be a ccnpy.flic.PresharedKeyCtx')
        if auth_tag is None:
            raise ValueError('auth_tag must not be None')
        if not isinstance(auth_tag, ccnpy.flic.AuthTag):
            raise TypeError('auth_tag must be ccnpy.flic.AuthTag')
        if security_ctx.key_number() != self._key_number:
            raise ValueError('security_ctx.key_number %r != our key_number %r' % (security_ctx.key_number(), self._key_number))
        plaintext = self._key.decrypt(nonce=security_ctx.iv(), ciphertext=encrypted_node.value(), associated_data=security_ctx.serialize(), auth_tag=auth_tag.value())
        node_tlv = ccnpy.Tlv(ccnpy.flic.Node.class_type(), plaintext)
        node = ccnpy.flic.Node.parse(node_tlv)
        return node
<|end_body_3|>

<|body_start_4|>
        if not isinstance(encrypted_manifest, ccnpy.flic.Manifest):
            raise TypeError('encrypted_manifest must be ccnpy.flic.Manifest')
        security_ctx = encrypted_manifest.security_ctx()
        encrypted_node = encrypted_manifest.node()
        auth_tag = encrypted_manifest.auth_tag()
        if not isinstance(encrypted_node, ccnpy.flic.EncryptedNode):
            raise TypeError('manifest did not contain an encrypted node')
        if security_ctx is None:
            raise ValueError('security context must not be None')
        if not isinstance(security_ctx, PresharedKeyCtx):
            raise TypeError('security_ctx must be a ccnpy.flic.PresharedKeyCtx')
        if auth_tag is None:
            raise ValueError('auth_tag must not be None')
        node = self.decrypt_node(security_ctx=security_ctx, encrypted_node=encrypted_node, auth_tag=auth_tag)
        manifest = ccnpy.flic.Manifest(node=node)
        return manifest
<|end_body_4|>

Solution:
class PresharedKey:
    """The PresharedKey algorithm. Typically, you will use `PresharedKey.create_manifest(...)` to create a Manifest TLV out of a ccnpy.flic.Node."""

    def __init__(self, key, key_number):
        """:param key: A ccnpy.crypto.AesGcmKey :param key_number: An integer used to reference the key"""
        if not isinstance(key, ccnpy.crypto.AesGcmKey):
            raise TypeError('key must be ccnpy.crypto.AesGcmKey')
        self._key = key
        self._key_number = key_number

    def encrypt(self, node):
        """:param node: A ccnpy.flic.Node :return: (security_ctx, encrypted_node, auth_tag)"""
        if not isinstance(node, ccnpy.flic.Node):
            raise TypeError('node must be ccnpy.flic.Node')
        plaintext = node.serialized_value()
        iv = self._key.nonce()
        security_ctx = None
        if len(self._key) == 128:
            security_ctx = PresharedKeyCtx.create_aes_gcm_128(key_number=self._key_number, iv=iv)
        elif len(self._key) == 256:
            security_ctx = PresharedKeyCtx.create_aes_gcm_256(key_number=self._key_number, iv=iv)
        else:
            raise ValueError('Unsupported key length %r' % len(self._key))
        ciphertext, a = self._key.encrypt(nonce=iv, plaintext=plaintext, associated_data=security_ctx.serialize())
        encrypted_node = ccnpy.flic.EncryptedNode(ciphertext)
        auth_tag = ccnpy.flic.AuthTag(a)
        return (security_ctx, encrypted_node, auth_tag)

    def create_encrypted_manifest(self, node):
        """:param node: A ccnpy.flic.Node to encrypt and wrap in a Manifest :return: A ccnpy.flic.Manifest"""
        security_ctx, encrypted_node, auth_tag = self.encrypt(node)
        manifest = ccnpy.flic.Manifest(security_ctx=security_ctx, node=encrypted_node, auth_tag=auth_tag)
        return manifest

    def decrypt_node(self, security_ctx, encrypted_node, auth_tag):
        """Example: manifest = ccnpy.flic.Manifest.deserialize(payload.value()) if isinstance(manifest.security_ctx(), ccnpy.flic.PresharedKeyCtx): # keystore is not necessarily provided key = keystore.get(manifest.security_ctx().key_number()) psk = ccnpy.flic.PresharedKey(key) node = psk.decrypt_node(manifest.security_ctx(), manifest.node(), manifest.auth_tag()) :param security_ctx: A ccnpy.flic.PresharedKeyCtx :param encrypted_node: A ccnpy.flic.EncryptedNode :param auth_tag: A ccnpy.flic.AuthTag :return: a ccnpy.flic.Node"""
        if not isinstance(encrypted_node, ccnpy.flic.EncryptedNode):
            raise TypeError('encrypted_node must be ccnpy.flic.EncryptedNode')
        if security_ctx is None:
            raise ValueError('security context must not be None')
        if not isinstance(security_ctx, ccnpy.flic.presharedkey.PresharedKeyCtx):
            raise TypeError('security_ctx must be a ccnpy.flic.PresharedKeyCtx')
        if auth_tag is None:
            raise ValueError('auth_tag must not be None')
        if not isinstance(auth_tag, ccnpy.flic.AuthTag):
            raise TypeError('auth_tag must be ccnpy.flic.AuthTag')
        if security_ctx.key_number() != self._key_number:
            raise ValueError('security_ctx.key_number %r != our key_number %r' % (security_ctx.key_number(), self._key_number))
        plaintext = self._key.decrypt(nonce=security_ctx.iv(), ciphertext=encrypted_node.value(), associated_data=security_ctx.serialize(), auth_tag=auth_tag.value())
        node_tlv = ccnpy.Tlv(ccnpy.flic.Node.class_type(), plaintext)
        node = ccnpy.flic.Node.parse(node_tlv)
        return node

    def decrypt_manifest(self, encrypted_manifest):
        """Example: manifest = ccnpy.flic.Manifest.deserialize(payload.value()) if isinstance(manifest.security_ctx(), ccnpy.flic.PresharedKeyCtx): # keystore is not necessarily provided key = keystore.get(manifest.security_ctx().key_number()) psk = ccnpy.flic.PresharedKey(key) manifest = psk.decrypt_to_manifest(manifest) :param encrypted_manifest: :return: A decrypted manifest"""
        if not isinstance(encrypted_manifest, ccnpy.flic.Manifest):
            raise TypeError('encrypted_manifest must be ccnpy.flic.Manifest')
        security_ctx = encrypted_manifest.security_ctx()
        encrypted_node = encrypted_manifest.node()
        auth_tag = encrypted_manifest.auth_tag()
        if not isinstance(encrypted_node, ccnpy.flic.EncryptedNode):
            raise TypeError('manifest did not contain an encrypted node')
        if security_ctx is None:
            raise ValueError('security context must not be None')
        if not isinstance(security_ctx, PresharedKeyCtx):
            raise TypeError('security_ctx must be a ccnpy.flic.PresharedKeyCtx')
        if auth_tag is None:
            raise ValueError('auth_tag must not be None')
        node = self.decrypt_node(security_ctx=security_ctx, encrypted_node=encrypted_node, auth_tag=auth_tag)
        manifest = ccnpy.flic.Manifest(node=node)
        return manifest


crawler

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

Class description:
Implement the Scheduler class.

Method signatures and docstrings:
- def __init__(self): 初始化调度器
- def crawler(self, root_url): 根据入口文件，开始爬取需要的内容和urls :param root_url: :return:

Implement the Python class `Scheduler` described below.

Class description:
Implement the Scheduler class.

Method signatures and docstrings:
- def __init__(self): 初始化调度器
- def crawler(self, root_url): 根据入口文件，开始爬取需要的内容和urls :param root_url: :return:

<|skeleton|>
class Scheduler:

    def __init__(self):
        """初始化调度器"""
        <|body_0|>

    def crawler(self, root_url):
        """根据入口文件，开始爬取需要的内容和urls :param root_url: :return:"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.urls = urls.Urls()
        self.parserHTML = Parser()
        self.output = Output()
<|end_body_0|>

<|body_start_1|>
        self.urls.add_new_url(root_url)
        while self.urls.get_new_urls_length() > 0:
            try:
                url = self.urls.get_new_url()
                flag, content = download.download(url)
                if flag:
                    links, datas = self.parserHTML.parser_html(url, content)
                    self.urls.add_new_urls(links)
                    self.output.store_datas(datas)
                else:
                    print(content)
            except Exception as e:
                print(e, 'crawler fail')
        self.output.to_html()
<|end_body_1|>

Solution:
class Scheduler:
    def __init__(self):
        """初始化调度器"""
        self.urls = urls.Urls()
        self.parserHTML = Parser()
        self.output = Output()

    def crawler(self, root_url):
        """根据入口文件，开始爬取需要的内容和urls :param root_url: :return:"""
        self.urls.add_new_url(root_url)
        while self.urls.get_new_urls_length() > 0:
            try:
                url = self.urls.get_new_url()
                flag, content = download.download(url)
                if flag:
                    links, datas = self.parserHTML.parser_html(url, content)
                    self.urls.add_new_urls(links)
                    self.output.store_datas(datas)
                else:
                    print(content)
            except Exception as e:
                print(e, 'crawler fail')
        self.output.to_html()


spawn

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

Class description:
Encapsulation of launching an MPI job using {mpirun}

Method signatures and docstrings:
- def launch(self, application, *args, **kwds): Launch {application} as a collection of mpi tasks
- def parallel(self, *args, **kwds): Called after the parallel machine has been built and it is time to invoke the user's code in every node
- def spawn(self, application, *args, **kwds): Invoke {mpirun} with the correct arguments to create the parallel machine
- def buildCommandLine(self): Construct the mpirun command line

Implement the Python class `Launcher` described below.

Class description:
Encapsulation of launching an MPI job using {mpirun}

Method signatures and docstrings:
- def launch(self, application, *args, **kwds): Launch {application} as a collection of mpi tasks
- def parallel(self, *args, **kwds): Called after the parallel machine has been built and it is time to invoke the user's code in every node
- def spawn(self, application, *args, **kwds): Invoke {mpirun} with the correct arguments to create the parallel machine
- def buildCommandLine(self): Construct the mpirun command line

<|skeleton|>
class Launcher:
    """Encapsulation of launching an MPI job using {mpirun}"""

    def launch(self, application, *args, **kwds):
        """Launch {application} as a collection of mpi tasks"""
        <|body_0|>

    def parallel(self, *args, **kwds):
        """Called after the parallel machine has been built and it is time to invoke the user's code in every node"""
        <|body_1|>

    def spawn(self, application, *args, **kwds):
        """Invoke {mpirun} with the correct arguments to create the parallel machine"""
        <|body_2|>

    def buildCommandLine(self):
        """Construct the mpirun command line"""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        if self.auto:
            try:
                application.pyre_mpi(*args, **kwds)
            except AttributeError:
                pass
            return self.spawn(*args, application=application, **kwds)
        return self.parallel(*args, application=application, **kwds)
<|end_body_0|>

<|body_start_1|>
        import mpi
        if mpi.init():
            self.world = mpi.world
            return super().launch(*args, **kwds)
        import journal
        channel = journal.error('mpi.init')
        channel.log('failed to initialize the mpi runtime support')
        return 1
<|end_body_1|>

<|body_start_2|>
        argv = self.buildCommandLine()
        options = {'args': argv, 'universal_newlines': True, 'shell': False}
        status = 42
        with subprocess.Popen(**options) as child:
            status = child.wait()
        return status
<|end_body_2|>

<|body_start_3|>
        launcher = self.mpi.launcher
        interpreter = sys.executable
        hosts = self.hosts
        tasks = self.tasks
        hostfile = self.hostfile
        extra = self.extra
        argv = [launcher]
        argv += ['-n', str(hosts * tasks)]
        if hostfile:
            argv += ['--hostfile', str(hostfile)]
        if extra:
            argv += extra.split()
        argv += [interpreter]
        argv += sys.argv
        argv += [f'--shell.hosts={hosts}', f'--shell.tasks={tasks}']
        argv += [f'--shell.auto=no']
        return argv
<|end_body_3|>

Solution:
class Launcher:
    """Encapsulation of launching an MPI job using {mpirun}"""

    def launch(self, application, *args, **kwds):
        """Launch {application} as a collection of mpi tasks"""
        if self.auto:
            try:
                application.pyre_mpi(*args, **kwds)
            except AttributeError:
                pass
            return self.spawn(*args, application=application, **kwds)
        return self.parallel(*args, application=application, **kwds)

    def parallel(self, *args, **kwds):
        """Called after the parallel machine has been built and it is time to invoke the user's code in every node"""
        import mpi
        if mpi.init():
            self.world = mpi.world
            return super().launch(*args, **kwds)
        import journal
        channel = journal.error('mpi.init')
        channel.log('failed to initialize the mpi runtime support')
        return 1

    def spawn(self, application, *args, **kwds):
        """Invoke {mpirun} with the correct arguments to create the parallel machine"""
        argv = self.buildCommandLine()
        options = {'args': argv, 'universal_newlines': True, 'shell': False}
        status = 42
        with subprocess.Popen(**options) as child:
            status = child.wait()
        return status

    def buildCommandLine(self):
        """Construct the mpirun command line"""
        launcher = self.mpi.launcher
        interpreter = sys.executable
        hosts = self.hosts
        tasks = self.tasks
        hostfile = self.hostfile
        extra = self.extra
        argv = [launcher]
        argv += ['-n', str(hosts * tasks)]
        if hostfile:
            argv += ['--hostfile', str(hostfile)]
        if extra:
            argv += extra.split()
        argv += [interpreter]
        argv += sys.argv
        argv += [f'--shell.hosts={hosts}', f'--shell.tasks={tasks}']
        argv += [f'--shell.auto=no']
        return argv


cdf

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

Class description:
define class

Method signatures and docstrings:
- def __init__(self, data=None, lambtha=1.0): class constructor
- def pmf(self, k): function that calculates the probability mass function for k successes
- def fact(self, k): function that returns the factorial of k
- def cdf(self, k): function that calculates the cumulative distribution function for k successes

Implement the Python class `Poisson` described below.

Class description:
define class

Method signatures and docstrings:
- def __init__(self, data=None, lambtha=1.0): class constructor
- def pmf(self, k): function that calculates the probability mass function for k successes
- def fact(self, k): function that returns the factorial of k
- def cdf(self, k): function that calculates the cumulative distribution function for k successes

<|skeleton|>
class Poisson:
    """define class"""

    def __init__(self, data=None, lambtha=1.0):
        """class constructor"""
        <|body_0|>

    def pmf(self, k):
        """function that calculates the probability mass function for k successes"""
        <|body_1|>

    def fact(self, k):
        """function that returns the factorial of k"""
        <|body_2|>

    def cdf(self, k):
        """function that calculates the cumulative distribution function for k successes"""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        if data is None and isinstance(lambtha, (float, int)):
            if lambtha <= 0:
                raise ValueError('lambtha must be a positive value')
            self.lambtha = float(lambtha)
        elif data is not None:
            if not isinstance(data, list):
                raise TypeError('data must be a list')
            if len(data) < 2:
                raise ValueError('data must contain multiple values')
            self.lambtha = float(sum(data) / len(data))
<|end_body_0|>

<|body_start_1|>
        if not isinstance(k, int):
            k = int(k)
        if k is None or k < 0:
            return 0
        return self.lambtha ** k * Poisson.e ** (-1 * self.lambtha) / self.fact(k)
<|end_body_1|>

<|body_start_2|>
        if k in [0, 1]:
            return 1
        return k * self.fact(k - 1)
<|end_body_2|>

<|body_start_3|>
        if not isinstance(k, int):
            k = int(k)
        if k is None or k < 0:
            return 0
        return Poisson.e ** (-1 * self.lambtha) * sum([self.lambtha ** i / self.fact(i) for i in range(0, k + 1)])
<|end_body_3|>

Solution:
class Poisson:
    """define class"""

    def __init__(self, data=None, lambtha=1.0):
        """class constructor"""
        if data is None and isinstance(lambtha, (float, int)):
            if lambtha <= 0:
                raise ValueError('lambtha must be a positive value')
            self.lambtha = float(lambtha)
        elif data is not None:
            if not isinstance(data, list):
                raise TypeError('data must be a list')
            if len(data) < 2:
                raise ValueError('data must contain multiple values')
            self.lambtha = float(sum(data) / len(data))

    def pmf(self, k):
        """function that calculates the probability mass function for k successes"""
        if not isinstance(k, int):
            k = int(k)
        if k is None or k < 0:
            return 0
        return self.lambtha ** k * Poisson.e ** (-1 * self.lambtha) / self.fact(k)

    def fact(self, k):
        """function that returns the factorial of k"""
        if k in [0, 1]:
            return 1
        return k * self.fact(k - 1)

    def cdf(self, k):
        """function that calculates the cumulative distribution function for k successes"""
        if not isinstance(k, int):
            k = int(k)
        if k is None or k < 0:
            return 0
        return Poisson.e ** (-1 * self.lambtha) * sum([self.lambtha ** i / self.fact(i) for i in range(0, k + 1)])


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

Class description:
Define an Airzone Zone select.

Method signatures and docstrings:
- def __init__(self, coordinator: AirzoneUpdateCoordinator, description: AirzoneSelectDescription, entry: ConfigEntry, system_zone_id: str, zone_data: dict[str, Any]) -> None: Initialize.
- async def async_select_option(self, option: str) -> None: Change the selected option.

Implement the Python class `AirzoneZoneSelect` described below.

Class description:
Define an Airzone Zone select.

Method signatures and docstrings:
- def __init__(self, coordinator: AirzoneUpdateCoordinator, description: AirzoneSelectDescription, entry: ConfigEntry, system_zone_id: str, zone_data: dict[str, Any]) -> None: Initialize.
- async def async_select_option(self, option: str) -> None: Change the selected option.

<|skeleton|>
class AirzoneZoneSelect:
    """Define an Airzone Zone select."""

    def __init__(self, coordinator: AirzoneUpdateCoordinator, description: AirzoneSelectDescription, entry: ConfigEntry, system_zone_id: str, zone_data: dict[str, Any]) -> None:
        """Initialize."""
        <|body_0|>

    async def async_select_option(self, option: str) -> None:
        """Change the selected option."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        super().__init__(coordinator, entry, system_zone_id, zone_data)
        self._attr_name = f'{zone_data[AZD_NAME]} {description.name}'
        self._attr_unique_id = f'{self._attr_unique_id}_{system_zone_id}_{description.key}'
        self.entity_description = description
        self.values_dict = {v: k for k, v in description.options_dict.items()}
        self._async_update_attrs()
<|end_body_0|>

<|body_start_1|>
        param = self.entity_description.api_param
        value = self.entity_description.options_dict[option]
        await self._async_update_hvac_params({param: value})
<|end_body_1|>

Solution:
class AirzoneZoneSelect:
    """Define an Airzone Zone select."""

    def __init__(self, coordinator: AirzoneUpdateCoordinator, description: AirzoneSelectDescription, entry: ConfigEntry, system_zone_id: str, zone_data: dict[str, Any]) -> None:
        """Initialize."""
        super().__init__(coordinator, entry, system_zone_id, zone_data)
        self._attr_name = f'{zone_data[AZD_NAME]} {description.name}'
        self._attr_unique_id = f'{self._attr_unique_id}_{system_zone_id}_{description.key}'
        self.entity_description = description
        self.values_dict = {v: k for k, v in description.options_dict.items()}
        self._async_update_attrs()

    async def async_select_option(self, option: str) -> None:
        """Change the selected option."""
        param = self.entity_description.api_param
        value = self.entity_description.options_dict[option]
        await self._async_update_hvac_params({param: value})


conform

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

Class description:
provides functionality for saving figures to file. from pyphoplacecellanalysis.General.Pipeline.Stages.Display import PipelineWithDisplaySavingMixin

Method signatures and docstrings:
- def build_display_context_for_session(self, display_fn_name: str, **kwargs) -> 'IdentifyingContext': builds a new display context for the session out of kwargs Usage: curr_active_pipeline.build_display_context_for_session(display_fn_name='DecodedEpochSlices', epochs='replays', decoder='long_results_obj')
- def build_display_context_for_filtered_session(self, filtered_session_name: str, display_fn_name: str, **kwargs) -> 'IdentifyingContext': builds a new display context for a filtered session out of kwargs Usage: curr_active_pipeline.build_display_context_for_session(display_fn_name='DecodedEpochSlices', epochs='replays', decoder='long_results_obj')
- def output_figure(self, final_context: IdentifyingContext, fig, write_vector_format: bool=False, write_png: bool=True, debug_print=True): outputs the figure using the provided context.
- def conform(cls, obj): makes the object conform to this mixin by adding its properties. Usage: from pyphoplacecellanalysis.General.Pipeline.Stages.Computation import PipelineWithComputedPipelineStageMixin, ComputedPipelineStage from pyphoplacecellanalysis.General.Pipeline.Stages.Display import PipelineWithDisplayPipelineStageMixin, PipelineWithDisplaySavingMixin from pyphoplacecellanalysis.General.Pipeline.Stages.Filtering import FilteredPipelineMixin from pyphoplacecellanalysis.General.Pipeline.Stages.Loading import PipelineWithInputStage, PipelineWithLoadableStage from pyphoplacecellanalysis.General.Pipeline.Stages.BaseNeuropyPipelineStage import PipelineStage from pyphoplacecellanalysis.General.Pipeline.Neuropy

Implement the Python class `PipelineWithDisplaySavingMixin` described below.

Class description:
provides functionality for saving figures to file. from pyphoplacecellanalysis.General.Pipeline.Stages.Display import PipelineWithDisplaySavingMixin

Method signatures and docstrings:
- def build_display_context_for_session(self, display_fn_name: str, **kwargs) -> 'IdentifyingContext': builds a new display context for the session out of kwargs Usage: curr_active_pipeline.build_display_context_for_session(display_fn_name='DecodedEpochSlices', epochs='replays', decoder='long_results_obj')
- def build_display_context_for_filtered_session(self, filtered_session_name: str, display_fn_name: str, **kwargs) -> 'IdentifyingContext': builds a new display context for a filtered session out of kwargs Usage: curr_active_pipeline.build_display_context_for_session(display_fn_name='DecodedEpochSlices', epochs='replays', decoder='long_results_obj')
- def output_figure(self, final_context: IdentifyingContext, fig, write_vector_format: bool=False, write_png: bool=True, debug_print=True): outputs the figure using the provided context.
- def conform(cls, obj): makes the object conform to this mixin by adding its properties. Usage: from pyphoplacecellanalysis.General.Pipeline.Stages.Computation import PipelineWithComputedPipelineStageMixin, ComputedPipelineStage from pyphoplacecellanalysis.General.Pipeline.Stages.Display import PipelineWithDisplayPipelineStageMixin, PipelineWithDisplaySavingMixin from pyphoplacecellanalysis.General.Pipeline.Stages.Filtering import FilteredPipelineMixin from pyphoplacecellanalysis.General.Pipeline.Stages.Loading import PipelineWithInputStage, PipelineWithLoadableStage from pyphoplacecellanalysis.General.Pipeline.Stages.BaseNeuropyPipelineStage import PipelineStage from pyphoplacecellanalysis.General.Pipeline.Neuropy

<|skeleton|>
class PipelineWithDisplaySavingMixin:
    """provides functionality for saving figures to file. from pyphoplacecellanalysis.General.Pipeline.Stages.Display import PipelineWithDisplaySavingMixin"""

    def build_display_context_for_session(self, display_fn_name: str, **kwargs) -> 'IdentifyingContext':
        """builds a new display context for the session out of kwargs Usage: curr_active_pipeline.build_display_context_for_session(display_fn_name='DecodedEpochSlices', epochs='replays', decoder='long_results_obj')"""
        <|body_0|>

    def build_display_context_for_filtered_session(self, filtered_session_name: str, display_fn_name: str, **kwargs) -> 'IdentifyingContext':
        """builds a new display context for a filtered session out of kwargs Usage: curr_active_pipeline.build_display_context_for_session(display_fn_name='DecodedEpochSlices', epochs='replays', decoder='long_results_obj')"""
        <|body_1|>

    def output_figure(self, final_context: IdentifyingContext, fig, write_vector_format: bool=False, write_png: bool=True, debug_print=True):
        """outputs the figure using the provided context."""
        <|body_2|>

    def conform(cls, obj):
        """makes the object conform to this mixin by adding its properties. Usage: from pyphoplacecellanalysis.General.Pipeline.Stages.Computation import PipelineWithComputedPipelineStageMixin, ComputedPipelineStage from pyphoplacecellanalysis.General.Pipeline.Stages.Display import PipelineWithDisplayPipelineStageMixin, PipelineWithDisplaySavingMixin from pyphoplacecellanalysis.General.Pipeline.Stages.Filtering import FilteredPipelineMixin from pyphoplacecellanalysis.General.Pipeline.Stages.Loading import PipelineWithInputStage, PipelineWithLoadableStage from pyphoplacecellanalysis.General.Pipeline.Stages.BaseNeuropyPipelineStage import PipelineStage from pyphoplacecellanalysis.General.Pipeline.Neuropy"""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        assert isinstance(display_fn_name, str), '"display_fn_name" must be provided as a string.'
        active_identifying_session_ctx = self.sess.get_context()
        display_subcontext = IdentifyingContext(display_fn_name=display_fn_name, **kwargs)
        return active_identifying_session_ctx.merging_context('display_', display_subcontext)
<|end_body_0|>

<|body_start_1|>
        assert isinstance(display_fn_name, str), '"display_fn_name" must be provided as a string.'
        active_identifying_session_ctx = self.filtered_contexts[filtered_session_name]
        display_subcontext = IdentifyingContext(display_fn_name=display_fn_name, **kwargs)
        return active_identifying_session_ctx.merging_context('display_', display_subcontext)
<|end_body_1|>

<|body_start_2|>
        from pyphoplacecellanalysis.General.Mixins.ExportHelpers import build_and_write_to_file
        active_out_figure_paths = build_and_write_to_file(fig, final_context, self.get_output_manager(), write_vector_format=write_vector_format, write_png=write_png, register_output_file_fn=self.register_output_file)
        return (active_out_figure_paths, final_context)
<|end_body_2|>

<|body_start_3|>
        def conform_to_implementing_method(func):
            """ captures 'obj', 'cls'"""
            setattr(type(obj), func.__name__, func)
        conform_to_implementing_method(cls.build_display_context_for_session)
        conform_to_implementing_method(cls.build_display_context_for_filtered_session)
        conform_to_implementing_method(cls.output_figure)
<|end_body_3|>

Solution:
class PipelineWithDisplaySavingMixin:
    """provides functionality for saving figures to file. from pyphoplacecellanalysis.General.Pipeline.Stages.Display import PipelineWithDisplaySavingMixin"""

    def build_display_context_for_session(self, display_fn_name: str, **kwargs) -> 'IdentifyingContext':
        """builds a new display context for the session out of kwargs Usage: curr_active_pipeline.build_display_context_for_session(display_fn_name='DecodedEpochSlices', epochs='replays', decoder='long_results_obj')"""
        assert isinstance(display_fn_name, str), '"display_fn_name" must be provided as a string.'
        active_identifying_session_ctx = self.sess.get_context()
        display_subcontext = IdentifyingContext(display_fn_name=display_fn_name, **kwargs)
        return active_identifying_session_ctx.merging_context('display_', display_subcontext)

    def build_display_context_for_filtered_session(self, filtered_session_name: str, display_fn_name: str, **kwargs) -> 'IdentifyingContext':
        """builds a new display context for a filtered session out of kwargs Usage: curr_active_pipeline.build_display_context_for_session(display_fn_name='DecodedEpochSlices', epochs='replays', decoder='long_results_obj')"""
        assert isinstance(display_fn_name, str), '"display_fn_name" must be provided as a string.'
        active_identifying_session_ctx = self.filtered_contexts[filtered_session_name]
        display_subcontext = IdentifyingContext(display_fn_name=display_fn_name, **kwargs)
        return active_identifying_session_ctx.merging_context('display_', display_subcontext)

    def output_figure(self, final_context: IdentifyingContext, fig, write_vector_format: bool=False, write_png: bool=True, debug_print=True):
        """outputs the figure using the provided context."""
        from pyphoplacecellanalysis.General.Mixins.ExportHelpers import build_and_write_to_file
        active_out_figure_paths = build_and_write_to_file(fig, final_context, self.get_output_manager(), write_vector_format=write_vector_format, write_png=write_png, register_output_file_fn=self.register_output_file)
        return (active_out_figure_paths, final_context)

    def conform(cls, obj):
        """makes the object conform to this mixin by adding its properties. Usage: from pyphoplacecellanalysis.General.Pipeline.Stages.Computation import PipelineWithComputedPipelineStageMixin, ComputedPipelineStage from pyphoplacecellanalysis.General.Pipeline.Stages.Display import PipelineWithDisplayPipelineStageMixin, PipelineWithDisplaySavingMixin from pyphoplacecellanalysis.General.Pipeline.Stages.Filtering import FilteredPipelineMixin from pyphoplacecellanalysis.General.Pipeline.Stages.Loading import PipelineWithInputStage, PipelineWithLoadableStage from pyphoplacecellanalysis.General.Pipeline.Stages.BaseNeuropyPipelineStage import PipelineStage from pyphoplacecellanalysis.General.Pipeline.Neuropy"""
        def conform_to_implementing_method(func):
            """ captures 'obj', 'cls'"""
            setattr(type(obj), func.__name__, func)
        conform_to_implementing_method(cls.build_display_context_for_session)
        conform_to_implementing_method(cls.build_display_context_for_filtered_session)
        conform_to_implementing_method(cls.output_figure)


forward

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

Class description:
Implement the InfoGAN_Generator class.

Method signatures and docstrings:
- def __init__(self, noise_dim=10, n_layer=3, n_conti=2, n_discrete=1, num_category=10, use_gpu=False, featmap_dim=256, n_channel=1): InfoGAN Generator, have an additional input branch for latent codes. Architecture brought from DCGAN.
- def forward(self, x): Input the random noise plus latent codes to generate fake images.

Implement the Python class `InfoGAN_Generator` described below.

Class description:
Implement the InfoGAN_Generator class.

Method signatures and docstrings:
- def __init__(self, noise_dim=10, n_layer=3, n_conti=2, n_discrete=1, num_category=10, use_gpu=False, featmap_dim=256, n_channel=1): InfoGAN Generator, have an additional input branch for latent codes. Architecture brought from DCGAN.
- def forward(self, x): Input the random noise plus latent codes to generate fake images.

<|skeleton|>
class InfoGAN_Generator:

    def __init__(self, noise_dim=10, n_layer=3, n_conti=2, n_discrete=1, num_category=10, use_gpu=False, featmap_dim=256, n_channel=1):
        """InfoGAN Generator, have an additional input branch for latent codes. Architecture brought from DCGAN."""
        <|body_0|>

    def forward(self, x):
        """Input the random noise plus latent codes to generate fake images."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        super(InfoGAN_Generator, self).__init__()
        self.n_layer = n_layer
        self.n_conti = n_conti
        self.n_discrete = n_discrete
        self.num_category = num_category
        n_input = noise_dim + n_conti + n_discrete * num_category
        self.featmap_dim = featmap_dim
        self.fc_in = nn.Linear(n_input, featmap_dim * 4 * 4)
        convs = []
        BNs = []
        for layer in range(self.n_layer):
            if layer == 0:
                n_conv_out = n_channel
            else:
                n_conv_out = featmap_dim / 2 ** (self.n_layer - layer)
            n_conv_in = featmap_dim / 2 ** (self.n_layer - layer - 1)
            n_width = 5 if layer == self.n_layer - 1 else 6
            _conv = nn.ConvTranspose2d(n_conv_in, n_conv_out, n_width, stride=2, padding=2)
            if use_gpu:
                _conv = _conv
            convs.append(_conv)
            if layer != 0:
                _BN = nn.BatchNorm2d(n_conv_out)
                if use_gpu:
                    _BN = _BN
                BNs.append(_BN)
        self.convs = nn.ModuleList(convs)
        self.BNs = nn.ModuleList(BNs)
<|end_body_0|>

<|body_start_1|>
        x = self.fc_in(x)
        x = x.view(-1, self.featmap_dim, 4, 4)
        for layer in range(self.n_layer):
            conv_layer = self.convs[self.n_layer - layer - 1]
            if layer == self.n_layer - 1:
                x = F.tanh(conv_layer(x))
            else:
                BN_layer = self.BNs[self.n_layer - layer - 2]
                x = F.relu(BN_layer(conv_layer(x)))
        return x
<|end_body_1|>

Solution:
class InfoGAN_Generator:
    def __init__(self, noise_dim=10, n_layer=3, n_conti=2, n_discrete=1, num_category=10, use_gpu=False, featmap_dim=256, n_channel=1):
        """InfoGAN Generator, have an additional input branch for latent codes. Architecture brought from DCGAN."""
        super(InfoGAN_Generator, self).__init__()
        self.n_layer = n_layer
        self.n_conti = n_conti
        self.n_discrete = n_discrete
        self.num_category = num_category
        n_input = noise_dim + n_conti + n_discrete * num_category
        self.featmap_dim = featmap_dim
        self.fc_in = nn.Linear(n_input, featmap_dim * 4 * 4)
        convs = []
        BNs = []
        for layer in range(self.n_layer):
            if layer == 0:
                n_conv_out = n_channel
            else:
                n_conv_out = featmap_dim / 2 ** (self.n_layer - layer)
            n_conv_in = featmap_dim / 2 ** (self.n_layer - layer - 1)
            n_width = 5 if layer == self.n_layer - 1 else 6
            _conv = nn.ConvTranspose2d(n_conv_in, n_conv_out, n_width, stride=2, padding=2)
            if use_gpu:
                _conv = _conv
            convs.append(_conv)
            if layer != 0:
                _BN = nn.BatchNorm2d(n_conv_out)
                if use_gpu:
                    _BN = _BN
                BNs.append(_BN)
        self.convs = nn.ModuleList(convs)
        self.BNs = nn.ModuleList(BNs)

    def forward(self, x):
        """Input the random noise plus latent codes to generate fake images."""
        x = self.fc_in(x)
        x = x.view(-1, self.featmap_dim, 4, 4)
        for layer in range(self.n_layer):
            conv_layer = self.convs[self.n_layer - layer - 1]
            if layer == self.n_layer - 1:
                x = F.tanh(conv_layer(x))
            else:
                BN_layer = self.BNs[self.n_layer - layer - 2]
                x = F.relu(BN_layer(conv_layer(x)))
        return x


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

Class description:
Test the prepare_for_integration method.

Method signatures and docstrings:
- def setUp(self): Set up the cube.
- def test_basic(self): Test that the type of the returned value is as expected and the expected number of items are returned.
- def test_positive_points(self): Test that the expected coordinate points are returned for each cube when the direction of integration is positive.
- def test_negative_points(self): Test that the expected coordinate points are returned for each cube when the direction of integration is negative.

Implement the Python class `Test_prepare_for_integration` described below.

Class description:
Test the prepare_for_integration method.

Method signatures and docstrings:
- def setUp(self): Set up the cube.
- def test_basic(self): Test that the type of the returned value is as expected and the expected number of items are returned.
- def test_positive_points(self): Test that the expected coordinate points are returned for each cube when the direction of integration is positive.
- def test_negative_points(self): Test that the expected coordinate points are returned for each cube when the direction of integration is negative.

<|skeleton|>
class Test_prepare_for_integration:
    """Test the prepare_for_integration method."""

    def setUp(self):
        """Set up the cube."""
        <|body_0|>

    def test_basic(self):
        """Test that the type of the returned value is as expected and the expected number of items are returned."""
        <|body_1|>

    def test_positive_points(self):
        """Test that the expected coordinate points are returned for each cube when the direction of integration is positive."""
        <|body_2|>

    def test_negative_points(self):
        """Test that the expected coordinate points are returned for each cube when the direction of integration is negative."""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        height_points = np.array([5.0, 10.0, 20.0])
        cube = _set_up_height_cube(height_points)
        self.plugin_positive = Integration('height', positive_integration=True)
        self.plugin_positive.input_cube = cube.copy()
        self.plugin_negative = Integration('height')
        self.plugin_negative.input_cube = cube.copy()
<|end_body_0|>

<|body_start_1|>
        result = self.plugin_negative.prepare_for_integration()
        self.assertIsInstance(result, tuple)
        self.assertEqual(len(result), 2)
        self.assertIsInstance(result[0], iris.cube.Cube)
        self.assertIsInstance(result[1], iris.cube.Cube)
<|end_body_1|>

<|body_start_2|>
        result = self.plugin_positive.prepare_for_integration()
        self.assertArrayAlmostEqual(result[0].coord('height').points, np.array([10.0, 20.0]))
        self.assertArrayAlmostEqual(result[1].coord('height').points, np.array([5.0, 10.0]))
<|end_body_2|>

<|body_start_3|>
        self.plugin_negative.input_cube.coord('height').points = np.array([20.0, 10.0, 5.0])
        result = self.plugin_negative.prepare_for_integration()
        self.assertArrayAlmostEqual(result[0].coord('height').points, np.array([20.0, 10.0]))
        self.assertArrayAlmostEqual(result[1].coord('height').points, np.array([10.0, 5.0]))
<|end_body_3|>

Solution:
class Test_prepare_for_integration:
    """Test the prepare_for_integration method."""

    def setUp(self):
        """Set up the cube."""
        height_points = np.array([5.0, 10.0, 20.0])
        cube = _set_up_height_cube(height_points)
        self.plugin_positive = Integration('height', positive_integration=True)
        self.plugin_positive.input_cube = cube.copy()
        self.plugin_negative = Integration('height')
        self.plugin_negative.input_cube = cube.copy()

    def test_basic(self):
        """Test that the type of the returned value is as expected and the expected number of items are returned."""
        result = self.plugin_negative.prepare_for_integration()
        self.assertIsInstance(result, tuple)
        self.assertEqual(len(result), 2)
        self.assertIsInstance(result[0], iris.cube.Cube)
        self.assertIsInstance(result[1], iris.cube.Cube)

    def test_positive_points(self):
        """Test that the expected coordinate points are returned for each cube when the direction of integration is positive."""
        result = self.plugin_positive.prepare_for_integration()
        self.assertArrayAlmostEqual(result[0].coord('height').points, np.array([10.0, 20.0]))
        self.assertArrayAlmostEqual(result[1].coord('height').points, np.array([5.0, 10.0]))

    def test_negative_points(self):
        """Test that the expected coordinate points are returned for each cube when the direction of integration is negative."""
        self.plugin_negative.input_cube.coord('height').points = np.array([20.0, 10.0, 5.0])
        result = self.plugin_negative.prepare_for_integration()
        self.assertArrayAlmostEqual(result[0].coord('height').points, np.array([20.0, 10.0]))
        self.assertArrayAlmostEqual(result[1].coord('height').points, np.array([10.0, 5.0]))


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

Class description:
Test the URL encoded RPC mapper.

Method signatures and docstrings:
- def testBuildRequest_Prefix(self): Test building request with parameter prefix.
- def testBuildRequest_DecodeError(self): Test trying to build request that causes a decode error.
- def testBuildResponse_Prefix(self): Test building a response with parameter prefix.

Implement the Python class `URLEncodedRPCMapperTest` described below.

Class description:
Test the URL encoded RPC mapper.

Method signatures and docstrings:
- def testBuildRequest_Prefix(self): Test building request with parameter prefix.
- def testBuildRequest_DecodeError(self): Test trying to build request that causes a decode error.
- def testBuildResponse_Prefix(self): Test building a response with parameter prefix.

<|skeleton|>
class URLEncodedRPCMapperTest:
    """Test the URL encoded RPC mapper."""

    def testBuildRequest_Prefix(self):
        """Test building request with parameter prefix."""
        <|body_0|>

    def testBuildRequest_DecodeError(self):
        """Test trying to build request that causes a decode error."""
        <|body_1|>

    def testBuildResponse_Prefix(self):
        """Test building a response with parameter prefix."""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        self.Reinitialize(urllib.urlencode([('prefix_integer_field', '10'), ('prefix_string_field', 'a string'), ('prefix_enum_field', 'VAL1')]), self.content_type)
        url_encoded_mapper = service_handlers.URLEncodedRPCMapper(parameter_prefix='prefix_')
        request = url_encoded_mapper.build_request(self.service_handler, Request1)
        self.assertEquals(10, request.integer_field)
        self.assertEquals('a string', request.string_field)
        self.assertEquals(Enum1.VAL1, request.enum_field)
<|end_body_0|>

<|body_start_1|>
        self.Reinitialize(urllib.urlencode((('integer_field', '10'), ('integer_field', '20'))), content_type=self.content_type)
        url_encoded_mapper = service_handlers.URLEncodedRPCMapper()
        self.assertRaises(service_handlers.RequestError, url_encoded_mapper.build_request, self.service_handler, Service.method1.remote.request_type)
<|end_body_1|>

<|body_start_2|>
        response = Response1()
        response.integer_field = 10
        response.string_field = u'a string'
        response.enum_field = Enum1.VAL3
        url_encoded_mapper = service_handlers.URLEncodedRPCMapper(parameter_prefix='prefix_')
        url_encoded_mapper.build_response(self.service_handler, response)
        self.assertEquals('application/x-www-form-urlencoded', self.response.headers['content-type'])
        self.assertEquals(cgi.parse_qs(self.response.out.getvalue(), True, True), {'prefix_integer_field': ['10'], 'prefix_string_field': [u'a string'], 'prefix_enum_field': ['VAL3']})
<|end_body_2|>

Solution:
class URLEncodedRPCMapperTest:
    """Test the URL encoded RPC mapper."""

    def testBuildRequest_Prefix(self):
        """Test building request with parameter prefix."""
        self.Reinitialize(urllib.urlencode([('prefix_integer_field', '10'), ('prefix_string_field', 'a string'), ('prefix_enum_field', 'VAL1')]), self.content_type)
        url_encoded_mapper = service_handlers.URLEncodedRPCMapper(parameter_prefix='prefix_')
        request = url_encoded_mapper.build_request(self.service_handler, Request1)
        self.assertEquals(10, request.integer_field)
        self.assertEquals('a string', request.string_field)
        self.assertEquals(Enum1.VAL1, request.enum_field)

    def testBuildRequest_DecodeError(self):
        """Test trying to build request that causes a decode error."""
        self.Reinitialize(urllib.urlencode((('integer_field', '10'), ('integer_field', '20'))), content_type=self.content_type)
        url_encoded_mapper = service_handlers.URLEncodedRPCMapper()
        self.assertRaises(service_handlers.RequestError, url_encoded_mapper.build_request, self.service_handler, Service.method1.remote.request_type)

    def testBuildResponse_Prefix(self):
        """Test building a response with parameter prefix."""
        response = Response1()
        response.integer_field = 10
        response.string_field = u'a string'
        response.enum_field = Enum1.VAL3
        url_encoded_mapper = service_handlers.URLEncodedRPCMapper(parameter_prefix='prefix_')
        url_encoded_mapper.build_response(self.service_handler, response)
        self.assertEquals('application/x-www-form-urlencoded', self.response.headers['content-type'])
        self.assertEquals(cgi.parse_qs(self.response.out.getvalue(), True, True), {'prefix_integer_field': ['10'], 'prefix_string_field': [u'a string'], 'prefix_enum_field': ['VAL3']})


predict

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

Class description:
Naive model with drift for time-series forecasting. In the drift model, the forecasts are equal to the last observation of a given time-series plus an additional value proportional to the forecasted timestamp. The attributed to the timestamp is estimated from the first and last observation of the given time-series.

Method signatures and docstrings:
- def __init__(self): Init a Naive model with drift.
- def fit(self, X: np.ndarray, y: np.ndarray, **kwargs) -> 'TSNaiveDrift': Fit a Naive model with drift. This model calculates the slope of the line crossing the first and last observation of ``y``, and stores it alongside the last observation value of ``y`` and its timestamp. This is equivalent of calculating the mean of the slopes between each pair of adjacent observation, since it is a telescoping sum, and use it as the model drift coefficient.
- def predict(self, X: np.ndarray) -> np.ndarray: Predict new observations from the timestamps 'X'.

Implement the Python class `TSNaiveDrift` described below.

Class description:
Naive model with drift for time-series forecasting. In the drift model, the forecasts are equal to the last observation of a given time-series plus an additional value proportional to the forecasted timestamp. The attributed to the timestamp is estimated from the first and last observation of the given time-series.

Method signatures and docstrings:
- def __init__(self): Init a Naive model with drift.
- def fit(self, X: np.ndarray, y: np.ndarray, **kwargs) -> 'TSNaiveDrift': Fit a Naive model with drift. This model calculates the slope of the line crossing the first and last observation of ``y``, and stores it alongside the last observation value of ``y`` and its timestamp. This is equivalent of calculating the mean of the slopes between each pair of adjacent observation, since it is a telescoping sum, and use it as the model drift coefficient.
- def predict(self, X: np.ndarray) -> np.ndarray: Predict new observations from the timestamps 'X'.

<|skeleton|>
class TSNaiveDrift:
    """Naive model with drift for time-series forecasting. In the drift model, the forecasts are equal to the last observation of a given time-series plus an additional value proportional to the forecasted timestamp. The attributed to the timestamp is estimated from the first and last observation of the given time-series."""

    def __init__(self):
        """Init a Naive model with drift."""
        <|body_0|>

    def fit(self, X: np.ndarray, y: np.ndarray, **kwargs) -> 'TSNaiveDrift':
        """Fit a Naive model with drift. This model calculates the slope of the line crossing the first and last observation of ``y``, and stores it alongside the last observation value of ``y`` and its timestamp. This is equivalent of calculating the mean of the slopes between each pair of adjacent observation, since it is a telescoping sum, and use it as the model drift coefficient."""
        <|body_1|>

    def predict(self, X: np.ndarray) -> np.ndarray:
        """Predict new observations from the timestamps 'X'."""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        self.slope = -1.0
        self.last_obs = -1.0
        self.last_obs_ind = -1
        self._fitted = False
<|end_body_0|>

<|body_start_1|>
        if X.size != y.size:
            raise ValueError("'X' and 'y' size must match.")
        self.last_obs = y[-1]
        self.last_obs_ind = X[-1]
        if y.size > 1:
            self.slope = (y[-1] - y[0]) / (X[-1] - X[0])
        else:
            self.slope = 0.0
        self._fitted = True
        return self
<|end_body_1|>

<|body_start_2|>
        if not self._fitted:
            raise ValueError('Model is not fitted.')
        diff_timestamps = X - self.last_obs_ind
        if np.any(diff_timestamps < 0):
            raise ValueError('Timestamps must be higher than the last fitted timestamp ({}).'.format(self.last_obs_ind))
        return self.last_obs + diff_timestamps * self.slope
<|end_body_2|>

Solution:
class TSNaiveDrift:
    """Naive model with drift for time-series forecasting. In the drift model, the forecasts are equal to the last observation of a given time-series plus an additional value proportional to the forecasted timestamp. The attributed to the timestamp is estimated from the first and last observation of the given time-series."""

    def __init__(self):
        """Init a Naive model with drift."""
        self.slope = -1.0
        self.last_obs = -1.0
        self.last_obs_ind = -1
        self._fitted = False

    def fit(self, X: np.ndarray, y: np.ndarray, **kwargs) -> 'TSNaiveDrift':
        """Fit a Naive model with drift. This model calculates the slope of the line crossing the first and last observation of ``y``, and stores it alongside the last observation value of ``y`` and its timestamp. This is equivalent of calculating the mean of the slopes between each pair of adjacent observation, since it is a telescoping sum, and use it as the model drift coefficient."""
        if X.size != y.size:
            raise ValueError("'X' and 'y' size must match.")
        self.last_obs = y[-1]
        self.last_obs_ind = X[-1]
        if y.size > 1:
            self.slope = (y[-1] - y[0]) / (X[-1] - X[0])
        else:
            self.slope = 0.0
        self._fitted = True
        return self

    def predict(self, X: np.ndarray) -> np.ndarray:
        """Predict new observations from the timestamps 'X'."""
        if not self._fitted:
            raise ValueError('Model is not fitted.')
        diff_timestamps = X - self.last_obs_ind
        if np.any(diff_timestamps < 0):
            raise ValueError('Timestamps must be higher than the last fitted timestamp ({}).'.format(self.last_obs_ind))
        return self.last_obs + diff_timestamps * self.slope


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

Class description:
SeqClassificationTaskModel

Method signatures and docstrings:
- def __init__(self, class_num, model_config, encoder_model): __init__
- def forward(self, input, pos): forward

Implement the Python class `SeqClassificationTaskModel` described below.

Class description:
SeqClassificationTaskModel

Method signatures and docstrings:
- def __init__(self, class_num, model_config, encoder_model): __init__
- def forward(self, input, pos): forward

<|skeleton|>
class SeqClassificationTaskModel:
    """SeqClassificationTaskModel"""

    def __init__(self, class_num, model_config, encoder_model):
        """__init__"""
        <|body_0|>

    def forward(self, input, pos):
        """forward"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        super(SeqClassificationTaskModel, self).__init__()
        model_type = model_config.get('model_type', 'transformer')
        hidden_size = model_config.get('hidden_size', 512)
        in_channels = hidden_size * 2 if model_type == 'lstm' else hidden_size
        self.conv_decoder = nn.Sequential(nn.Conv1D(in_channels=in_channels, out_channels=128, kernel_size=5, padding='same', data_format='NLC'), nn.ReLU(), nn.Conv1D(in_channels=128, out_channels=class_num, kernel_size=3, padding='same', data_format='NLC'))
        self.encoder_model = encoder_model
<|end_body_0|>

<|body_start_1|>
        encoder_output = self.encoder_model(input, pos)
        decoder_output = self.conv_decoder(encoder_output)
        return decoder_output
<|end_body_1|>

Solution:
class SeqClassificationTaskModel:
    """SeqClassificationTaskModel"""

    def __init__(self, class_num, model_config, encoder_model):
        """__init__"""
        super(SeqClassificationTaskModel, self).__init__()
        model_type = model_config.get('model_type', 'transformer')
        hidden_size = model_config.get('hidden_size', 512)
        in_channels = hidden_size * 2 if model_type == 'lstm' else hidden_size
        self.conv_decoder = nn.Sequential(nn.Conv1D(in_channels=in_channels, out_channels=128, kernel_size=5, padding='same', data_format='NLC'), nn.ReLU(), nn.Conv1D(in_channels=128, out_channels=class_num, kernel_size=3, padding='same', data_format='NLC'))
        self.encoder_model = encoder_model

    def forward(self, input, pos):
        """forward"""
        encoder_output = self.encoder_model(input, pos)
        decoder_output = self.conv_decoder(encoder_output)
        return decoder_output