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

Class description:
Class for one image template

Method signatures and docstrings:
- def __init__(self, filename): Initializer for the class @param filename: name of the spectrum @type filename: string
- def _makeImgHDU(self, filename, imaname): Extract and return the first non-empty image HDU from the fits The method opens a fits image and goes along its extension. The first extension with a non-zero data part is returned after updating the header with a given image name. @param filename: name of the fits file @type filename: string @param imaname: name of the image @type imaname: string @return: the image hdu @rtype: hdu()
- def _norm_data(self, Imgdata): Normalize the image data The method normalizes the image data. It uses methods of the data class (numpy or numarray). @param Imgdata: the image data @type Imgdata: <ImgData()> @return: the normalized image data @rtype: <ImgData()>

Implement the Python class `ArtImage` described below.

Class description:
Class for one image template

Method signatures and docstrings:
- def __init__(self, filename): Initializer for the class @param filename: name of the spectrum @type filename: string
- def _makeImgHDU(self, filename, imaname): Extract and return the first non-empty image HDU from the fits The method opens a fits image and goes along its extension. The first extension with a non-zero data part is returned after updating the header with a given image name. @param filename: name of the fits file @type filename: string @param imaname: name of the image @type imaname: string @return: the image hdu @rtype: hdu()
- def _norm_data(self, Imgdata): Normalize the image data The method normalizes the image data. It uses methods of the data class (numpy or numarray). @param Imgdata: the image data @type Imgdata: <ImgData()> @return: the normalized image data @rtype: <ImgData()>

<|skeleton|>
class ArtImage:
    """Class for one image template"""

    def __init__(self, filename):
        """Initializer for the class @param filename: name of the spectrum @type filename: string"""
        <|body_0|>

    def _makeImgHDU(self, filename, imaname):
        """Extract and return the first non-empty image HDU from the fits The method opens a fits image and goes along its extension. The first extension with a non-zero data part is returned after updating the header with a given image name. @param filename: name of the fits file @type filename: string @param imaname: name of the image @type imaname: string @return: the image hdu @rtype: hdu()"""
        <|body_1|>

    def _norm_data(self, Imgdata):
        """Normalize the image data The method normalizes the image data. It uses methods of the data class (numpy or numarray). @param Imgdata: the image data @type Imgdata: <ImgData()> @return: the normalized image data @rtype: <ImgData()>"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        self.filename = filename
        self.imaname = os.path.basename(filename[:filename.rfind('.')])
        self.imgHDU = self._makeImgHDU(self.filename, self.imaname)
<|end_body_0|>

<|body_start_1|>
        imgHDU = None
        fitsHDU = pyfits.open(filename, 'update')
        index = 0
        for HDU in fitsHDU:
            if HDU.data != None:
                HDU.header['IMANAME'] = imaname
                normData = self._norm_data(HDU.data)
                imgHDU = pyfits.ImageHDU(normData, header=HDU.header, name=imaname)
                print('File %s, ext: %s loaded' % (filename, str(index)))
                break
        fitsHDU.close()
        return imgHDU
<|end_body_1|>

<|body_start_2|>
        cts_sum = Imgdata.sum()
        normData = Imgdata / cts_sum
        return normData
<|end_body_2|>

Solution:
class ArtImage:
    """Class for one image template"""

    def __init__(self, filename):
        """Initializer for the class @param filename: name of the spectrum @type filename: string"""
        self.filename = filename
        self.imaname = os.path.basename(filename[:filename.rfind('.')])
        self.imgHDU = self._makeImgHDU(self.filename, self.imaname)

    def _makeImgHDU(self, filename, imaname):
        """Extract and return the first non-empty image HDU from the fits The method opens a fits image and goes along its extension. The first extension with a non-zero data part is returned after updating the header with a given image name. @param filename: name of the fits file @type filename: string @param imaname: name of the image @type imaname: string @return: the image hdu @rtype: hdu()"""
        imgHDU = None
        fitsHDU = pyfits.open(filename, 'update')
        index = 0
        for HDU in fitsHDU:
            if HDU.data != None:
                HDU.header['IMANAME'] = imaname
                normData = self._norm_data(HDU.data)
                imgHDU = pyfits.ImageHDU(normData, header=HDU.header, name=imaname)
                print('File %s, ext: %s loaded' % (filename, str(index)))
                break
        fitsHDU.close()
        return imgHDU

    def _norm_data(self, Imgdata):
        """Normalize the image data The method normalizes the image data. It uses methods of the data class (numpy or numarray). @param Imgdata: the image data @type Imgdata: <ImgData()> @return: the normalized image data @rtype: <ImgData()>"""
        cts_sum = Imgdata.sum()
        normData = Imgdata / cts_sum
        return normData


forward

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

Class description:
Relative attention layer. Layer that maps (location_bias, context_bias, pos_emb, q, k, v, mask) to (activations, mask). This layer type performs the inner workings of one pass of multi-head self-attention. It: - splits queries, keys, and values into multiple 'heads', - splits positional embeddings into multiple 'heads', - computes per-head attention weights from per-head (queries, keys), - applies mask to screen out positions that come from padding tokens, - [in `'train'` mode] applies dropout to attention weights, - uses attention weights to combine per-head values vectors, and - merges per-head results into outgoing activations matching original input activation vector shapes.

Method signatures and docstrings:
- def __init__(self, separate_cls, n_heads=1, dropout=0.0, mode='train'): Returns a new PureAttention instance. Args: separate_cls: True/False if we separate_cls in calculations. n_heads: Number of attention heads. dropout: Probabilistic rate for dropout applied to attention strengths (based on query-key pairs) before applying them to values. mode: One of `'train'`, `'eval'`, or `'predict'`.
- def forward(self, inputs): Returns attention-computed activations and unmodified mask. Args: inputs: A (location_bias, context_bias, pos_emb, q, k, v, mask) tuple.

Implement the Python class `RelativeAttention` described below.

Class description:
Relative attention layer. Layer that maps (location_bias, context_bias, pos_emb, q, k, v, mask) to (activations, mask). This layer type performs the inner workings of one pass of multi-head self-attention. It: - splits queries, keys, and values into multiple 'heads', - splits positional embeddings into multiple 'heads', - computes per-head attention weights from per-head (queries, keys), - applies mask to screen out positions that come from padding tokens, - [in `'train'` mode] applies dropout to attention weights, - uses attention weights to combine per-head values vectors, and - merges per-head results into outgoing activations matching original input activation vector shapes.

Method signatures and docstrings:
- def __init__(self, separate_cls, n_heads=1, dropout=0.0, mode='train'): Returns a new PureAttention instance. Args: separate_cls: True/False if we separate_cls in calculations. n_heads: Number of attention heads. dropout: Probabilistic rate for dropout applied to attention strengths (based on query-key pairs) before applying them to values. mode: One of `'train'`, `'eval'`, or `'predict'`.
- def forward(self, inputs): Returns attention-computed activations and unmodified mask. Args: inputs: A (location_bias, context_bias, pos_emb, q, k, v, mask) tuple.

<|skeleton|>
class RelativeAttention:
    """Relative attention layer. Layer that maps (location_bias, context_bias, pos_emb, q, k, v, mask) to (activations, mask). This layer type performs the inner workings of one pass of multi-head self-attention. It: - splits queries, keys, and values into multiple 'heads', - splits positional embeddings into multiple 'heads', - computes per-head attention weights from per-head (queries, keys), - applies mask to screen out positions that come from padding tokens, - [in `'train'` mode] applies dropout to attention weights, - uses attention weights to combine per-head values vectors, and - merges per-head results into outgoing activations matching original input activation vector shapes."""

    def __init__(self, separate_cls, n_heads=1, dropout=0.0, mode='train'):
        """Returns a new PureAttention instance. Args: separate_cls: True/False if we separate_cls in calculations. n_heads: Number of attention heads. dropout: Probabilistic rate for dropout applied to attention strengths (based on query-key pairs) before applying them to values. mode: One of `'train'`, `'eval'`, or `'predict'`."""
        <|body_0|>

    def forward(self, inputs):
        """Returns attention-computed activations and unmodified mask. Args: inputs: A (location_bias, context_bias, pos_emb, q, k, v, mask) tuple."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        super().__init__(n_in=7, n_out=2)
        self._separate_cls = separate_cls
        self._n_heads = n_heads
        self._dropout = dropout
        self._mode = mode
<|end_body_0|>

<|body_start_1|>
        location_bias, context_bias, pos_emb, q, k, v, mask = inputs
        d_feature = q.shape[-1]
        n_heads = self._n_heads
        if d_feature % n_heads != 0:
            raise ValueError(f'Dimensionality of feature embedding ({d_feature}) is not a multiple of the requested number of attention heads ({n_heads}).')
        per_head_results, dots = DotProductAttention(SplitIntoHeads(n_heads, merged_batch_and_head=False).forward(q), SplitIntoHeads(n_heads, merged_batch_and_head=False).forward(k), SplitIntoHeads(n_heads, merged_batch_and_head=False).forward(v), pos_emb.reshape((-1, n_heads, d_feature // n_heads)), context_bias, location_bias, mask, separate_cls=self._separate_cls, dropout=self._dropout, mode=self._mode, rng=self.rng)
        if self._mode == 'viz':
            self.state = dots
        merged_results = MergeHeads(n_heads, merged_batch_and_head=False).forward(per_head_results)
        return (merged_results, mask)
<|end_body_1|>

Solution:
class RelativeAttention:
    """Relative attention layer. Layer that maps (location_bias, context_bias, pos_emb, q, k, v, mask) to (activations, mask). This layer type performs the inner workings of one pass of multi-head self-attention. It: - splits queries, keys, and values into multiple 'heads', - splits positional embeddings into multiple 'heads', - computes per-head attention weights from per-head (queries, keys), - applies mask to screen out positions that come from padding tokens, - [in `'train'` mode] applies dropout to attention weights, - uses attention weights to combine per-head values vectors, and - merges per-head results into outgoing activations matching original input activation vector shapes."""

    def __init__(self, separate_cls, n_heads=1, dropout=0.0, mode='train'):
        """Returns a new PureAttention instance. Args: separate_cls: True/False if we separate_cls in calculations. n_heads: Number of attention heads. dropout: Probabilistic rate for dropout applied to attention strengths (based on query-key pairs) before applying them to values. mode: One of `'train'`, `'eval'`, or `'predict'`."""
        super().__init__(n_in=7, n_out=2)
        self._separate_cls = separate_cls
        self._n_heads = n_heads
        self._dropout = dropout
        self._mode = mode

    def forward(self, inputs):
        """Returns attention-computed activations and unmodified mask. Args: inputs: A (location_bias, context_bias, pos_emb, q, k, v, mask) tuple."""
        location_bias, context_bias, pos_emb, q, k, v, mask = inputs
        d_feature = q.shape[-1]
        n_heads = self._n_heads
        if d_feature % n_heads != 0:
            raise ValueError(f'Dimensionality of feature embedding ({d_feature}) is not a multiple of the requested number of attention heads ({n_heads}).')
        per_head_results, dots = DotProductAttention(SplitIntoHeads(n_heads, merged_batch_and_head=False).forward(q), SplitIntoHeads(n_heads, merged_batch_and_head=False).forward(k), SplitIntoHeads(n_heads, merged_batch_and_head=False).forward(v), pos_emb.reshape((-1, n_heads, d_feature // n_heads)), context_bias, location_bias, mask, separate_cls=self._separate_cls, dropout=self._dropout, mode=self._mode, rng=self.rng)
        if self._mode == 'viz':
            self.state = dots
        merged_results = MergeHeads(n_heads, merged_batch_and_head=False).forward(per_head_results)
        return (merged_results, mask)


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

Class description:
Implement the GestorTag class.

Method signatures and docstrings:
- def obtener_tags_script(self, p_id_script): Dado el identificador de un Script. Obtenemos los Tags asociados al mismo :param p_id_script: El identificador del script :return:
- def obtener_scripts_del_tag(self, p_id_tag): Dado el identificador de un Tag. Obtenemos la lista de Scripts asociada al mismo :param p_id_tag: :return:
- def borrar_tag(self, p_id_tag): Dado el identificador de un TAg. Borra del sistema el TAg :param p_id_tag: El identificador de un TAg :return:

Implement the Python class `GestorTag` described below.

Class description:
Implement the GestorTag class.

Method signatures and docstrings:
- def obtener_tags_script(self, p_id_script): Dado el identificador de un Script. Obtenemos los Tags asociados al mismo :param p_id_script: El identificador del script :return:
- def obtener_scripts_del_tag(self, p_id_tag): Dado el identificador de un Tag. Obtenemos la lista de Scripts asociada al mismo :param p_id_tag: :return:
- def borrar_tag(self, p_id_tag): Dado el identificador de un TAg. Borra del sistema el TAg :param p_id_tag: El identificador de un TAg :return:

<|skeleton|>
class GestorTag:

    def obtener_tags_script(self, p_id_script):
        """Dado el identificador de un Script. Obtenemos los Tags asociados al mismo :param p_id_script: El identificador del script :return:"""
        <|body_0|>

    def obtener_scripts_del_tag(self, p_id_tag):
        """Dado el identificador de un Tag. Obtenemos la lista de Scripts asociada al mismo :param p_id_tag: :return:"""
        <|body_1|>

    def borrar_tag(self, p_id_tag):
        """Dado el identificador de un TAg. Borra del sistema el TAg :param p_id_tag: El identificador de un TAg :return:"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        bd = MySQLConnector.MySQLConnector()
        consulta = ('SELECT IdTag FROM Tag_Script WHERE IdScript=%s', (p_id_script,))
        respuesta_bd = bd.execute(consulta)
        return respuesta_bd
<|end_body_0|>

<|body_start_1|>
        bd = MySQLConnector.MySQLConnector()
        consulta = ('SELECT IdScript FROM Tag_Script WHERE IdTag=%s', (p_id_tag,))
        respuesta_bd = bd.execute(consulta)
        return respuesta_bd
<|end_body_1|>

<|body_start_2|>
        bd = MySQLConnector.MySQLConnector()
        consulta = ('DELETE FROM Tag WHERE IdTag=%s', (p_id_tag,))
        respuesta_bd = bd.execute(consulta)
        return respuesta_bd
<|end_body_2|>

Solution:
class GestorTag:
    def obtener_tags_script(self, p_id_script):
        """Dado el identificador de un Script. Obtenemos los Tags asociados al mismo :param p_id_script: El identificador del script :return:"""
        bd = MySQLConnector.MySQLConnector()
        consulta = ('SELECT IdTag FROM Tag_Script WHERE IdScript=%s', (p_id_script,))
        respuesta_bd = bd.execute(consulta)
        return respuesta_bd

    def obtener_scripts_del_tag(self, p_id_tag):
        """Dado el identificador de un Tag. Obtenemos la lista de Scripts asociada al mismo :param p_id_tag: :return:"""
        bd = MySQLConnector.MySQLConnector()
        consulta = ('SELECT IdScript FROM Tag_Script WHERE IdTag=%s', (p_id_tag,))
        respuesta_bd = bd.execute(consulta)
        return respuesta_bd

    def borrar_tag(self, p_id_tag):
        """Dado el identificador de un TAg. Borra del sistema el TAg :param p_id_tag: El identificador de un TAg :return:"""
        bd = MySQLConnector.MySQLConnector()
        consulta = ('DELETE FROM Tag WHERE IdTag=%s', (p_id_tag,))
        respuesta_bd = bd.execute(consulta)
        return respuesta_bd


calculate

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

Class description:
Derivation of variable `toz`.

Method signatures and docstrings:
- def required(project): Declare the variables needed for derivation.
- def calculate(cubes): Compute total column ozone. Note ---- The surface pressure is used as a lower integration bound. A fixed upper integration bound of 0 Pa is used.

Implement the Python class `DerivedVariable` described below.

Class description:
Derivation of variable `toz`.

Method signatures and docstrings:
- def required(project): Declare the variables needed for derivation.
- def calculate(cubes): Compute total column ozone. Note ---- The surface pressure is used as a lower integration bound. A fixed upper integration bound of 0 Pa is used.

<|skeleton|>
class DerivedVariable:
    """Derivation of variable `toz`."""

    def required(project):
        """Declare the variables needed for derivation."""
        <|body_0|>

    def calculate(cubes):
        """Compute total column ozone. Note ---- The surface pressure is used as a lower integration bound. A fixed upper integration bound of 0 Pa is used."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        if project == 'CMIP6':
            required = [{'short_name': 'o3'}, {'short_name': 'ps'}]
        else:
            required = [{'short_name': 'tro3'}, {'short_name': 'ps'}]
        return required
<|end_body_0|>

<|body_start_1|>
        tro3_cube = cubes.extract_cube(iris.Constraint(name='mole_fraction_of_ozone_in_air'))
        ps_cube = cubes.extract_cube(iris.Constraint(name='surface_air_pressure'))
        p_layer_widths = pressure_level_widths(tro3_cube, ps_cube, top_limit=0.0)
        toz_cube = tro3_cube * p_layer_widths / STANDARD_GRAVITY * MW_O3 / MW_AIR
        toz_cube = toz_cube.collapsed('air_pressure', iris.analysis.SUM)
        toz_cube.units = tro3_cube.units * p_layer_widths.units / STANDARD_GRAVITY_UNIT * MW_O3_UNIT / MW_AIR_UNIT
        toz_cube = toz_cube / MW_O3 * AVOGADRO_CONST
        toz_cube.units = toz_cube.units / MW_O3_UNIT * AVOGADRO_CONST_UNIT
        toz_cube.convert_units(DOBSON_UNIT)
        toz_cube.units = 'DU'
        return toz_cube
<|end_body_1|>

Solution:
class DerivedVariable:
    """Derivation of variable `toz`."""

    def required(project):
        """Declare the variables needed for derivation."""
        if project == 'CMIP6':
            required = [{'short_name': 'o3'}, {'short_name': 'ps'}]
        else:
            required = [{'short_name': 'tro3'}, {'short_name': 'ps'}]
        return required

    def calculate(cubes):
        """Compute total column ozone. Note ---- The surface pressure is used as a lower integration bound. A fixed upper integration bound of 0 Pa is used."""
        tro3_cube = cubes.extract_cube(iris.Constraint(name='mole_fraction_of_ozone_in_air'))
        ps_cube = cubes.extract_cube(iris.Constraint(name='surface_air_pressure'))
        p_layer_widths = pressure_level_widths(tro3_cube, ps_cube, top_limit=0.0)
        toz_cube = tro3_cube * p_layer_widths / STANDARD_GRAVITY * MW_O3 / MW_AIR
        toz_cube = toz_cube.collapsed('air_pressure', iris.analysis.SUM)
        toz_cube.units = tro3_cube.units * p_layer_widths.units / STANDARD_GRAVITY_UNIT * MW_O3_UNIT / MW_AIR_UNIT
        toz_cube = toz_cube / MW_O3 * AVOGADRO_CONST
        toz_cube.units = toz_cube.units / MW_O3_UNIT * AVOGADRO_CONST_UNIT
        toz_cube.convert_units(DOBSON_UNIT)
        toz_cube.units = 'DU'
        return toz_cube


expression

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

Class description:
A class to get the rssi via an installed version of miller's rssi puller.

Method signatures and docstrings:
- def __init__(self, connection): :param: - `connection`: a connection to the windows device
- def expression(self): :return: compiled regular expression to match valid rssi output
- def validate(self, line): :parameter: - `line`: a line of output
- def __call__(self): :return: the rssi value :raises: CommandError if the rssi can't be retrieved.

Implement the Python class `WinRssi` described below.

Class description:
A class to get the rssi via an installed version of miller's rssi puller.

Method signatures and docstrings:
- def __init__(self, connection): :param: - `connection`: a connection to the windows device
- def expression(self): :return: compiled regular expression to match valid rssi output
- def validate(self, line): :parameter: - `line`: a line of output
- def __call__(self): :return: the rssi value :raises: CommandError if the rssi can't be retrieved.

<|skeleton|>
class WinRssi:
    """A class to get the rssi via an installed version of miller's rssi puller."""

    def __init__(self, connection):
        """:param: - `connection`: a connection to the windows device"""
        <|body_0|>

    def expression(self):
        """:return: compiled regular expression to match valid rssi output"""
        <|body_1|>

    def validate(self, line):
        """:parameter: - `line`: a line of output"""
        <|body_2|>

    def __call__(self):
        """:return: the rssi value :raises: CommandError if the rssi can't be retrieved."""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        super(WinRssi, self).__init__()
        self.connection = connection
        self._expression = None
        self.key = 'rssi'
        return
<|end_body_0|>

<|body_start_1|>
        if self._expression is None:
            self._expression = re.compile(oatbran.NAMED(n=self.key, e='-' + oatbran.INTEGER))
        return self._expression
<|end_body_1|>

<|body_start_2|>
        self.logger.debug('Validating: {0}'.format(line))
        if 'Unable to find the wireless interface.' in line:
            raise WinRssiError(line)
        if 'The group or resource is not in the correct state' in line:
            raise WinRssiError(line)
        return
<|end_body_2|>

<|body_start_3|>
        output = self.connection.wifi('rssi')
        for line in output.output:
            match = self.expression.search(line)
            if match:
                self.logger.debug('Matched: {0}'.format(line))
                return match.groupdict()[self.key]
            self.validate(line)
        return NA
<|end_body_3|>

Solution:
class WinRssi:
    """A class to get the rssi via an installed version of miller's rssi puller."""

    def __init__(self, connection):
        """:param: - `connection`: a connection to the windows device"""
        super(WinRssi, self).__init__()
        self.connection = connection
        self._expression = None
        self.key = 'rssi'
        return

    def expression(self):
        """:return: compiled regular expression to match valid rssi output"""
        if self._expression is None:
            self._expression = re.compile(oatbran.NAMED(n=self.key, e='-' + oatbran.INTEGER))
        return self._expression

    def validate(self, line):
        """:parameter: - `line`: a line of output"""
        self.logger.debug('Validating: {0}'.format(line))
        if 'Unable to find the wireless interface.' in line:
            raise WinRssiError(line)
        if 'The group or resource is not in the correct state' in line:
            raise WinRssiError(line)
        return

    def __call__(self):
        """:return: the rssi value :raises: CommandError if the rssi can't be retrieved."""
        output = self.connection.wifi('rssi')
        for line in output.output:
            match = self.expression.search(line)
            if match:
                self.logger.debug('Matched: {0}'.format(line))
                return match.groupdict()[self.key]
            self.validate(line)
        return NA


forward

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

Class description:
MNIST classifier used in the experiments for Counterfactual with Reinforcement Learning. The model consists of two convolutional layers having 64 and 32 channels and a kernel size of 2 with ReLU nonlinearities, followed by maxpooling of size 2 and dropout of 0.3. The convolutional block is followed by a fully connected layer of 256 with ReLU nonlinearity, and finally a fully connected layer is used to predict the class logits (10 in MNIST case).

Method signatures and docstrings:
- def __init__(self, output_dim: int) -> None: Constructor. Parameters ---------- output_dim Output dimension.
- def forward(self, x: torch.Tensor) -> torch.Tensor: Forward pass. Parameters ---------- x Input tensor. Returns ------- Classification logits.

Implement the Python class `MNISTClassifier` described below.

Class description:
MNIST classifier used in the experiments for Counterfactual with Reinforcement Learning. The model consists of two convolutional layers having 64 and 32 channels and a kernel size of 2 with ReLU nonlinearities, followed by maxpooling of size 2 and dropout of 0.3. The convolutional block is followed by a fully connected layer of 256 with ReLU nonlinearity, and finally a fully connected layer is used to predict the class logits (10 in MNIST case).

Method signatures and docstrings:
- def __init__(self, output_dim: int) -> None: Constructor. Parameters ---------- output_dim Output dimension.
- def forward(self, x: torch.Tensor) -> torch.Tensor: Forward pass. Parameters ---------- x Input tensor. Returns ------- Classification logits.

<|skeleton|>
class MNISTClassifier:
    """MNIST classifier used in the experiments for Counterfactual with Reinforcement Learning. The model consists of two convolutional layers having 64 and 32 channels and a kernel size of 2 with ReLU nonlinearities, followed by maxpooling of size 2 and dropout of 0.3. The convolutional block is followed by a fully connected layer of 256 with ReLU nonlinearity, and finally a fully connected layer is used to predict the class logits (10 in MNIST case)."""

    def __init__(self, output_dim: int) -> None:
        """Constructor. Parameters ---------- output_dim Output dimension."""
        <|body_0|>

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """Forward pass. Parameters ---------- x Input tensor. Returns ------- Classification logits."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        super().__init__()
        self.conv1 = nn.Conv2d(1, 64, kernel_size=(2, 2), padding=1)
        self.maxpool1 = nn.MaxPool2d(kernel_size=2, stride=2)
        self.dropout1 = nn.Dropout(0.3)
        self.conv2 = nn.Conv2d(64, 32, kernel_size=(2, 2), padding=1)
        self.maxpool2 = nn.MaxPool2d(kernel_size=2, stride=2)
        self.dropout2 = nn.Dropout(0.3)
        self.flatten = nn.Flatten()
        self.fc1 = nn.Linear(1568, 256)
        self.fc2 = nn.Linear(256, output_dim)
        self.to(self.device)
<|end_body_0|>

<|body_start_1|>
        x = self.dropout1(self.maxpool1(F.relu(self.conv1(x))))
        x = self.dropout2(self.maxpool2(F.relu(self.conv2(x))))
        x = self.flatten(x)
        x = F.relu(self.fc1(x))
        x = self.fc2(x)
        return x
<|end_body_1|>

Solution:
class MNISTClassifier:
    """MNIST classifier used in the experiments for Counterfactual with Reinforcement Learning. The model consists of two convolutional layers having 64 and 32 channels and a kernel size of 2 with ReLU nonlinearities, followed by maxpooling of size 2 and dropout of 0.3. The convolutional block is followed by a fully connected layer of 256 with ReLU nonlinearity, and finally a fully connected layer is used to predict the class logits (10 in MNIST case)."""

    def __init__(self, output_dim: int) -> None:
        """Constructor. Parameters ---------- output_dim Output dimension."""
        super().__init__()
        self.conv1 = nn.Conv2d(1, 64, kernel_size=(2, 2), padding=1)
        self.maxpool1 = nn.MaxPool2d(kernel_size=2, stride=2)
        self.dropout1 = nn.Dropout(0.3)
        self.conv2 = nn.Conv2d(64, 32, kernel_size=(2, 2), padding=1)
        self.maxpool2 = nn.MaxPool2d(kernel_size=2, stride=2)
        self.dropout2 = nn.Dropout(0.3)
        self.flatten = nn.Flatten()
        self.fc1 = nn.Linear(1568, 256)
        self.fc2 = nn.Linear(256, output_dim)
        self.to(self.device)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """Forward pass. Parameters ---------- x Input tensor. Returns ------- Classification logits."""
        x = self.dropout1(self.maxpool1(F.relu(self.conv1(x))))
        x = self.dropout2(self.maxpool2(F.relu(self.conv2(x))))
        x = self.flatten(x)
        x = F.relu(self.fc1(x))
        x = self.fc2(x)
        return x


detectCycle

2. 集合保存访问过的节点，额外的空间 O(N)

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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def detectCycle(self, head: ListNode) -> ListNode: 1. 快慢指针： 入环点的位置为 r，fast、slow 两个指针在环 a 处相遇，环长度 a+b slow 移动长度 l1=r+a，则 fast 移动长度 l2=r+a+b+a，l2=2*l1-->r=b
- def detectCycle2(self, head: ListNode) -> ListNode: 2. 集合保存访问过的节点，额外的空间 O(N)

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def detectCycle(self, head: ListNode) -> ListNode: 1. 快慢指针： 入环点的位置为 r，fast、slow 两个指针在环 a 处相遇，环长度 a+b slow 移动长度 l1=r+a，则 fast 移动长度 l2=r+a+b+a，l2=2*l1-->r=b
- def detectCycle2(self, head: ListNode) -> ListNode: 2. 集合保存访问过的节点，额外的空间 O(N)

<|skeleton|>
class Solution:

    def detectCycle(self, head: ListNode) -> ListNode:
        """1. 快慢指针： 入环点的位置为 r，fast、slow 两个指针在环 a 处相遇，环长度 a+b slow 移动长度 l1=r+a，则 fast 移动长度 l2=r+a+b+a，l2=2*l1-->r=b"""
        <|body_0|>

    def detectCycle2(self, head: ListNode) -> ListNode:
        """2. 集合保存访问过的节点，额外的空间 O(N)"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        fast, slow = (head, head)
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
            if fast == slow:
                start = head
                while start.next:
                    if slow == start:
                        return start
                    start = start.next
                    slow = slow.next
        return None
<|end_body_0|>

<|body_start_1|>
        nodeList = set()
        while head:
            if head in nodeList:
                return head
            nodeList.add(head)
            head = head.next
        return None
<|end_body_1|>

Solution:
class Solution:
    def detectCycle(self, head: ListNode) -> ListNode:
        """1. 快慢指针： 入环点的位置为 r，fast、slow 两个指针在环 a 处相遇，环长度 a+b slow 移动长度 l1=r+a，则 fast 移动长度 l2=r+a+b+a，l2=2*l1-->r=b"""
        fast, slow = (head, head)
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
            if fast == slow:
                start = head
                while start.next:
                    if slow == start:
                        return start
                    start = start.next
                    slow = slow.next
        return None

    def detectCycle2(self, head: ListNode) -> ListNode:
        """2. 集合保存访问过的节点，额外的空间 O(N)"""
        nodeList = set()
        while head:
            if head in nodeList:
                return head
            nodeList.add(head)
            head = head.next
        return None


plot

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

Class description:
Canadian Building Footprints dataset. The `Canadian Building Footprints <https://github.com/Microsoft/CanadianBuildingFootprints>`__ dataset contains 11,842,186 computer generated building footprints in all Canadian provinces and territories in GeoJSON format. This data is freely available for download and use.

Method signatures and docstrings:
- def __init__(self, root: str='data', crs: Optional[CRS]=None, res: float=1e-05, transforms: Optional[Callable[[dict[str, Any]], dict[str, Any]]]=None, download: bool=False, checksum: bool=False) -> None: Initialize a new Dataset instance. Args: root: root directory where dataset can be found crs: :term:`coordinate reference system (CRS)` to warp to (defaults to the CRS of the first file found) res: resolution of the dataset in units of CRS transforms: a function/transform that takes an input sample and returns a transformed version download: if True, download dataset and store it in the root directory checksum: if True, check the MD5 of the downloaded files (may be slow) Raises: FileNotFoundError: if no files are found in ``root`` RuntimeError: if ``download=False`` and data is not found, or ``checksum=True`` and checksums don't match
- def _check_integrity(self) -> bool: Check integrity of dataset. Returns: True if dataset files are found and/or MD5s match, else False
- def _download(self) -> None: Download the dataset and extract it.
- def plot(self, sample: dict[str, Any], show_titles: bool=True, suptitle: Optional[str]=None) -> plt.Figure: Plot a sample from the dataset. Args: sample: a sample returned by :meth:`VectorDataset.__getitem__` show_titles: flag indicating whether to show titles above each panel suptitle: optional string to use as a suptitle Returns: a matplotlib Figure with the rendered sample .. versionchanged:: 0.3 Method now takes a sample dict, not a Tensor. Additionally, it is possible to show subplot titles and/or use a custom suptitle.

Implement the Python class `CanadianBuildingFootprints` described below.

Class description:
Canadian Building Footprints dataset. The `Canadian Building Footprints <https://github.com/Microsoft/CanadianBuildingFootprints>`__ dataset contains 11,842,186 computer generated building footprints in all Canadian provinces and territories in GeoJSON format. This data is freely available for download and use.

Method signatures and docstrings:
- def __init__(self, root: str='data', crs: Optional[CRS]=None, res: float=1e-05, transforms: Optional[Callable[[dict[str, Any]], dict[str, Any]]]=None, download: bool=False, checksum: bool=False) -> None: Initialize a new Dataset instance. Args: root: root directory where dataset can be found crs: :term:`coordinate reference system (CRS)` to warp to (defaults to the CRS of the first file found) res: resolution of the dataset in units of CRS transforms: a function/transform that takes an input sample and returns a transformed version download: if True, download dataset and store it in the root directory checksum: if True, check the MD5 of the downloaded files (may be slow) Raises: FileNotFoundError: if no files are found in ``root`` RuntimeError: if ``download=False`` and data is not found, or ``checksum=True`` and checksums don't match
- def _check_integrity(self) -> bool: Check integrity of dataset. Returns: True if dataset files are found and/or MD5s match, else False
- def _download(self) -> None: Download the dataset and extract it.
- def plot(self, sample: dict[str, Any], show_titles: bool=True, suptitle: Optional[str]=None) -> plt.Figure: Plot a sample from the dataset. Args: sample: a sample returned by :meth:`VectorDataset.__getitem__` show_titles: flag indicating whether to show titles above each panel suptitle: optional string to use as a suptitle Returns: a matplotlib Figure with the rendered sample .. versionchanged:: 0.3 Method now takes a sample dict, not a Tensor. Additionally, it is possible to show subplot titles and/or use a custom suptitle.

<|skeleton|>
class CanadianBuildingFootprints:
    """Canadian Building Footprints dataset. The `Canadian Building Footprints <https://github.com/Microsoft/CanadianBuildingFootprints>`__ dataset contains 11,842,186 computer generated building footprints in all Canadian provinces and territories in GeoJSON format. This data is freely available for download and use."""

    def __init__(self, root: str='data', crs: Optional[CRS]=None, res: float=1e-05, transforms: Optional[Callable[[dict[str, Any]], dict[str, Any]]]=None, download: bool=False, checksum: bool=False) -> None:
        """Initialize a new Dataset instance. Args: root: root directory where dataset can be found crs: :term:`coordinate reference system (CRS)` to warp to (defaults to the CRS of the first file found) res: resolution of the dataset in units of CRS transforms: a function/transform that takes an input sample and returns a transformed version download: if True, download dataset and store it in the root directory checksum: if True, check the MD5 of the downloaded files (may be slow) Raises: FileNotFoundError: if no files are found in ``root`` RuntimeError: if ``download=False`` and data is not found, or ``checksum=True`` and checksums don't match"""
        <|body_0|>

    def _check_integrity(self) -> bool:
        """Check integrity of dataset. Returns: True if dataset files are found and/or MD5s match, else False"""
        <|body_1|>

    def _download(self) -> None:
        """Download the dataset and extract it."""
        <|body_2|>

    def plot(self, sample: dict[str, Any], show_titles: bool=True, suptitle: Optional[str]=None) -> plt.Figure:
        """Plot a sample from the dataset. Args: sample: a sample returned by :meth:`VectorDataset.__getitem__` show_titles: flag indicating whether to show titles above each panel suptitle: optional string to use as a suptitle Returns: a matplotlib Figure with the rendered sample .. versionchanged:: 0.3 Method now takes a sample dict, not a Tensor. Additionally, it is possible to show subplot titles and/or use a custom suptitle."""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        self.root = root
        self.checksum = checksum
        if download:
            self._download()
        if not self._check_integrity():
            raise RuntimeError('Dataset not found or corrupted. ' + 'You can use download=True to download it')
        super().__init__(root, crs, res, transforms)
<|end_body_0|>

<|body_start_1|>
        for prov_terr, md5 in zip(self.provinces_territories, self.md5s):
            filepath = os.path.join(self.root, prov_terr + '.zip')
            if not check_integrity(filepath, md5 if self.checksum else None):
                return False
        return True
<|end_body_1|>

<|body_start_2|>
        if self._check_integrity():
            print('Files already downloaded and verified')
            return
        for prov_terr, md5 in zip(self.provinces_territories, self.md5s):
            download_and_extract_archive(self.url + prov_terr + '.zip', self.root, md5=md5 if self.checksum else None)
<|end_body_2|>

<|body_start_3|>
        image = sample['mask'].squeeze(0)
        ncols = 1
        showing_prediction = 'prediction' in sample
        if showing_prediction:
            pred = sample['prediction'].squeeze(0)
            ncols = 2
        fig, axs = plt.subplots(nrows=1, ncols=ncols, figsize=(4, 4))
        if showing_prediction:
            axs[0].imshow(image)
            axs[0].axis('off')
            axs[1].imshow(pred)
            axs[1].axis('off')
            if show_titles:
                axs[0].set_title('Mask')
                axs[1].set_title('Prediction')
        else:
            axs.imshow(image)
            axs.axis('off')
            if show_titles:
                axs.set_title('Mask')
        if suptitle is not None:
            plt.suptitle(suptitle)
        return fig
<|end_body_3|>

Solution:
class CanadianBuildingFootprints:
    """Canadian Building Footprints dataset. The `Canadian Building Footprints <https://github.com/Microsoft/CanadianBuildingFootprints>`__ dataset contains 11,842,186 computer generated building footprints in all Canadian provinces and territories in GeoJSON format. This data is freely available for download and use."""

    def __init__(self, root: str='data', crs: Optional[CRS]=None, res: float=1e-05, transforms: Optional[Callable[[dict[str, Any]], dict[str, Any]]]=None, download: bool=False, checksum: bool=False) -> None:
        """Initialize a new Dataset instance. Args: root: root directory where dataset can be found crs: :term:`coordinate reference system (CRS)` to warp to (defaults to the CRS of the first file found) res: resolution of the dataset in units of CRS transforms: a function/transform that takes an input sample and returns a transformed version download: if True, download dataset and store it in the root directory checksum: if True, check the MD5 of the downloaded files (may be slow) Raises: FileNotFoundError: if no files are found in ``root`` RuntimeError: if ``download=False`` and data is not found, or ``checksum=True`` and checksums don't match"""
        self.root = root
        self.checksum = checksum
        if download:
            self._download()
        if not self._check_integrity():
            raise RuntimeError('Dataset not found or corrupted. ' + 'You can use download=True to download it')
        super().__init__(root, crs, res, transforms)

    def _check_integrity(self) -> bool:
        """Check integrity of dataset. Returns: True if dataset files are found and/or MD5s match, else False"""
        for prov_terr, md5 in zip(self.provinces_territories, self.md5s):
            filepath = os.path.join(self.root, prov_terr + '.zip')
            if not check_integrity(filepath, md5 if self.checksum else None):
                return False
        return True

    def _download(self) -> None:
        """Download the dataset and extract it."""
        if self._check_integrity():
            print('Files already downloaded and verified')
            return
        for prov_terr, md5 in zip(self.provinces_territories, self.md5s):
            download_and_extract_archive(self.url + prov_terr + '.zip', self.root, md5=md5 if self.checksum else None)

    def plot(self, sample: dict[str, Any], show_titles: bool=True, suptitle: Optional[str]=None) -> plt.Figure:
        """Plot a sample from the dataset. Args: sample: a sample returned by :meth:`VectorDataset.__getitem__` show_titles: flag indicating whether to show titles above each panel suptitle: optional string to use as a suptitle Returns: a matplotlib Figure with the rendered sample .. versionchanged:: 0.3 Method now takes a sample dict, not a Tensor. Additionally, it is possible to show subplot titles and/or use a custom suptitle."""
        image = sample['mask'].squeeze(0)
        ncols = 1
        showing_prediction = 'prediction' in sample
        if showing_prediction:
            pred = sample['prediction'].squeeze(0)
            ncols = 2
        fig, axs = plt.subplots(nrows=1, ncols=ncols, figsize=(4, 4))
        if showing_prediction:
            axs[0].imshow(image)
            axs[0].axis('off')
            axs[1].imshow(pred)
            axs[1].axis('off')
            if show_titles:
                axs[0].set_title('Mask')
                axs[1].set_title('Prediction')
        else:
            axs.imshow(image)
            axs.axis('off')
            if show_titles:
                axs.set_title('Mask')
        if suptitle is not None:
            plt.suptitle(suptitle)
        return fig


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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def meeting_node(self, head): 在链表存在环的前提下找到一快一慢指针相遇的结点, :param head: 链表的头结点 :return:
- def entry_node_of_loop(self, head): 找到环的入口结点 :param head: 链表头结点 :return:

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def meeting_node(self, head): 在链表存在环的前提下找到一快一慢指针相遇的结点, :param head: 链表的头结点 :return:
- def entry_node_of_loop(self, head): 找到环的入口结点 :param head: 链表头结点 :return:

<|skeleton|>
class Solution:

    def meeting_node(self, head):
        """在链表存在环的前提下找到一快一慢指针相遇的结点, :param head: 链表的头结点 :return:"""
        <|body_0|>

    def entry_node_of_loop(self, head):
        """找到环的入口结点 :param head: 链表头结点 :return:"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        if head is None:
            return None
        slow = head.next
        if slow is None:
            return None
        fast = slow.next
        while slow is not None and fast is not None:
            if slow == fast:
                return fast
            slow = slow.next
            fast = fast.next
            if fast is not None:
                fast = fast.next
        return None
<|end_body_0|>

<|body_start_1|>
        meet_node = self.meeting_node(head)
        if meet_node is None:
            return None
        loop_nodes = 1
        temp_node = meet_node
        while temp_node.next != meet_node:
            temp_node = temp_node.next
            loop_nodes += 1
        temp_node = head
        for i in range(loop_nodes):
            temp_node = temp_node.next
        temp_node2 = head
        while temp_node2 != temp_node:
            temp_node = temp_node.next
            temp_node2 = temp_node2.next
        return temp_node
<|end_body_1|>

Solution:
class Solution:
    def meeting_node(self, head):
        """在链表存在环的前提下找到一快一慢指针相遇的结点, :param head: 链表的头结点 :return:"""
        if head is None:
            return None
        slow = head.next
        if slow is None:
            return None
        fast = slow.next
        while slow is not None and fast is not None:
            if slow == fast:
                return fast
            slow = slow.next
            fast = fast.next
            if fast is not None:
                fast = fast.next
        return None

    def entry_node_of_loop(self, head):
        """找到环的入口结点 :param head: 链表头结点 :return:"""
        meet_node = self.meeting_node(head)
        if meet_node is None:
            return None
        loop_nodes = 1
        temp_node = meet_node
        while temp_node.next != meet_node:
            temp_node = temp_node.next
            loop_nodes += 1
        temp_node = head
        for i in range(loop_nodes):
            temp_node = temp_node.next
        temp_node2 = head
        while temp_node2 != temp_node:
            temp_node = temp_node.next
            temp_node2 = temp_node2.next
        return temp_node


transfer

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

Class description:
Implementation of wallet repository.

Method signatures and docstrings:
- async def get_by_id(self, wallet_id: int) -> Optional[WalletEntity]: Retrieve wallet record by wallet id. :param wallet_id: ID of use :returns: Wallet schema
- async def get_by_user_id(self, user_id: int) -> Optional[WalletEntity]: Retrieve wallet record by user id. :param user_id: ID of use :returns: Wallet schema
- async def create(self, user_id: int) -> int: Create new wallet with user ID :param user_id: ID of user :returns: ID of new wallet
- async def enroll(self, wallet_id: int, amount: Decimal) -> int: Put given funds on wallet :param wallet_id: ID of wallet :param amount: Initial funds :returns: ID of updated wallet
- async def transfer(self, source_wallet_id: int, destination_wallet_id: int, amount: Decimal) -> int: Transfer amount of currency between wallets. :param source_wallet_id: ID of source wallet :param destination_wallet_id: ID of wallet recepients :param amount: Amount of currency :returns: Source wallet id

Implement the Python class `WalletRepository` described below.

Class description:
Implementation of wallet repository.

Method signatures and docstrings:
- async def get_by_id(self, wallet_id: int) -> Optional[WalletEntity]: Retrieve wallet record by wallet id. :param wallet_id: ID of use :returns: Wallet schema
- async def get_by_user_id(self, user_id: int) -> Optional[WalletEntity]: Retrieve wallet record by user id. :param user_id: ID of use :returns: Wallet schema
- async def create(self, user_id: int) -> int: Create new wallet with user ID :param user_id: ID of user :returns: ID of new wallet
- async def enroll(self, wallet_id: int, amount: Decimal) -> int: Put given funds on wallet :param wallet_id: ID of wallet :param amount: Initial funds :returns: ID of updated wallet
- async def transfer(self, source_wallet_id: int, destination_wallet_id: int, amount: Decimal) -> int: Transfer amount of currency between wallets. :param source_wallet_id: ID of source wallet :param destination_wallet_id: ID of wallet recepients :param amount: Amount of currency :returns: Source wallet id

<|skeleton|>
class WalletRepository:
    """Implementation of wallet repository."""

    async def get_by_id(self, wallet_id: int) -> Optional[WalletEntity]:
        """Retrieve wallet record by wallet id. :param wallet_id: ID of use :returns: Wallet schema"""
        <|body_0|>

    async def get_by_user_id(self, user_id: int) -> Optional[WalletEntity]:
        """Retrieve wallet record by user id. :param user_id: ID of use :returns: Wallet schema"""
        <|body_1|>

    async def create(self, user_id: int) -> int:
        """Create new wallet with user ID :param user_id: ID of user :returns: ID of new wallet"""
        <|body_2|>

    async def enroll(self, wallet_id: int, amount: Decimal) -> int:
        """Put given funds on wallet :param wallet_id: ID of wallet :param amount: Initial funds :returns: ID of updated wallet"""
        <|body_3|>

    async def transfer(self, source_wallet_id: int, destination_wallet_id: int, amount: Decimal) -> int:
        """Transfer amount of currency between wallets. :param source_wallet_id: ID of source wallet :param destination_wallet_id: ID of wallet recepients :param amount: Amount of currency :returns: Source wallet id"""
        <|body_4|>

<|end_skeleton|>

<|body_start_0|>
        wallet_query = wallets.select().where(wallets.c.id == wallet_id)
        wallet = await self._db.fetch_one(wallet_query)
        if wallet:
            return WalletEntity(**wallet)
        return None
<|end_body_0|>

<|body_start_1|>
        wallet_query = wallets.select().where(wallets.c.user_id == user_id)
        wallet = await self._db.fetch_one(wallet_query)
        if wallet:
            return WalletEntity(**wallet)
        return None
<|end_body_1|>

<|body_start_2|>
        wallet_query = wallets.insert().values({'user_id': user_id})
        wallet_id: int = await self._db.execute(wallet_query)
        return wallet_id
<|end_body_2|>

<|body_start_3|>
        query = wallets.update().where(wallets.c.id == wallet_id).values({'balance': wallets.c.balance + amount}).returning(wallets.c.id)
        w_id: int = await self._db.execute(query)
        return w_id
<|end_body_3|>

<|body_start_4|>
        source_query = wallets.update().where(wallets.c.id == source_wallet_id).values({'balance': wallets.c.balance - amount}).returning(wallets.c.id)
        target_query = wallets.update().where(wallets.c.id == destination_wallet_id).values({'balance': wallets.c.balance + amount})
        wallet_id: int = await self._db.execute(source_query)
        if not wallet_id:
            raise ValueError('Source wallet id does not exist')
        await self._db.execute(target_query)
        return wallet_id
<|end_body_4|>

Solution:
class WalletRepository:
    """Implementation of wallet repository."""

    async def get_by_id(self, wallet_id: int) -> Optional[WalletEntity]:
        """Retrieve wallet record by wallet id. :param wallet_id: ID of use :returns: Wallet schema"""
        wallet_query = wallets.select().where(wallets.c.id == wallet_id)
        wallet = await self._db.fetch_one(wallet_query)
        if wallet:
            return WalletEntity(**wallet)
        return None

    async def get_by_user_id(self, user_id: int) -> Optional[WalletEntity]:
        """Retrieve wallet record by user id. :param user_id: ID of use :returns: Wallet schema"""
        wallet_query = wallets.select().where(wallets.c.user_id == user_id)
        wallet = await self._db.fetch_one(wallet_query)
        if wallet:
            return WalletEntity(**wallet)
        return None

    async def create(self, user_id: int) -> int:
        """Create new wallet with user ID :param user_id: ID of user :returns: ID of new wallet"""
        wallet_query = wallets.insert().values({'user_id': user_id})
        wallet_id: int = await self._db.execute(wallet_query)
        return wallet_id

    async def enroll(self, wallet_id: int, amount: Decimal) -> int:
        """Put given funds on wallet :param wallet_id: ID of wallet :param amount: Initial funds :returns: ID of updated wallet"""
        query = wallets.update().where(wallets.c.id == wallet_id).values({'balance': wallets.c.balance + amount}).returning(wallets.c.id)
        w_id: int = await self._db.execute(query)
        return w_id

    async def transfer(self, source_wallet_id: int, destination_wallet_id: int, amount: Decimal) -> int:
        """Transfer amount of currency between wallets. :param source_wallet_id: ID of source wallet :param destination_wallet_id: ID of wallet recepients :param amount: Amount of currency :returns: Source wallet id"""
        source_query = wallets.update().where(wallets.c.id == source_wallet_id).values({'balance': wallets.c.balance - amount}).returning(wallets.c.id)
        target_query = wallets.update().where(wallets.c.id == destination_wallet_id).values({'balance': wallets.c.balance + amount})
        wallet_id: int = await self._db.execute(source_query)
        if not wallet_id:
            raise ValueError('Source wallet id does not exist')
        await self._db.execute(target_query)
        return wallet_id


process

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

Class description:
AllowAllIamPolicies :example: .. code-block:: yaml policies: - name: cam-policy-overly-permissive resource: tencentcloud.cam-policy filters: - type: has-allow-all

Method signatures and docstrings:
- def has_allow_all_policy(self, resource): has_allow_all_policy
- def process(self, resources, event=None): process

Implement the Python class `AllowAllIamPolicies` described below.

Class description:
AllowAllIamPolicies :example: .. code-block:: yaml policies: - name: cam-policy-overly-permissive resource: tencentcloud.cam-policy filters: - type: has-allow-all

Method signatures and docstrings:
- def has_allow_all_policy(self, resource): has_allow_all_policy
- def process(self, resources, event=None): process

<|skeleton|>
class AllowAllIamPolicies:
    """AllowAllIamPolicies :example: .. code-block:: yaml policies: - name: cam-policy-overly-permissive resource: tencentcloud.cam-policy filters: - type: has-allow-all"""

    def has_allow_all_policy(self, resource):
        """has_allow_all_policy"""
        <|body_0|>

    def process(self, resources, event=None):
        """process"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.manager.get_policy_content(resource)
        for s in resource['PolicyDocument']['statement']:
            if 'condition' not in s and s['effect'] == 'allow':
                if 'action' in s and '*:*' in s['action'] and ('resource' in s) and (isinstance(s['resource'], str) and s['resource'] == '*' or (isinstance(s['resource'], list) and '*' in s['resource'])):
                    return True
        return False
<|end_body_0|>

<|body_start_1|>
        results = [r for r in resources if self.has_allow_all_policy(r)]
        self.log.info('%d of %d cam policies have allow all.', len(results), len(resources))
        return results
<|end_body_1|>

Solution:
class AllowAllIamPolicies:
    """AllowAllIamPolicies :example: .. code-block:: yaml policies: - name: cam-policy-overly-permissive resource: tencentcloud.cam-policy filters: - type: has-allow-all"""

    def has_allow_all_policy(self, resource):
        """has_allow_all_policy"""
        self.manager.get_policy_content(resource)
        for s in resource['PolicyDocument']['statement']:
            if 'condition' not in s and s['effect'] == 'allow':
                if 'action' in s and '*:*' in s['action'] and ('resource' in s) and (isinstance(s['resource'], str) and s['resource'] == '*' or (isinstance(s['resource'], list) and '*' in s['resource'])):
                    return True
        return False

    def process(self, resources, event=None):
        """process"""
        results = [r for r in resources if self.has_allow_all_policy(r)]
        self.log.info('%d of %d cam policies have allow all.', len(results), len(resources))
        return results


insertFields

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

Class description:
RecordForm for the GradeSurveyTakeForm.

Method signatures and docstrings:
- def getFields(self, *args): Add the extra grade field's value from survey_record.
- def insertFields(self): Add ordered fields to self.fields, add grade field with grade choices.

Implement the Python class `GradeSurveyRecordForm` described below.

Class description:
RecordForm for the GradeSurveyTakeForm.

Method signatures and docstrings:
- def getFields(self, *args): Add the extra grade field's value from survey_record.
- def insertFields(self): Add ordered fields to self.fields, add grade field with grade choices.

<|skeleton|>
class GradeSurveyRecordForm:
    """RecordForm for the GradeSurveyTakeForm."""

    def getFields(self, *args):
        """Add the extra grade field's value from survey_record."""
        <|body_0|>

    def insertFields(self):
        """Add ordered fields to self.fields, add grade field with grade choices."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        if hasattr(self.survey_record, 'grade'):
            grade = self.survey_record.grade
        vals_grade = {True: 'pass', False: 'fail'}
        self.data['grade'] = vals_grade.get(grade, None) or grade
        return super(GradeSurveyRecordForm, self).getFields(*args)
<|end_body_0|>

<|body_start_1|>
        fields = super(GradeSurveyRecordForm, self).insertFields()
        grade_choices = (('', 'Choose a Grade'),) + tuple(DEF_GRADE_CHOICES)
        gradeField = forms.fields.CharField(widget=custom_widgets.PlainTextWidget, initial=self.data.get('grade'))
        fields.insert(len(fields) + 1, 'grade', gradeField)
        return fields
<|end_body_1|>

Solution:
class GradeSurveyRecordForm:
    """RecordForm for the GradeSurveyTakeForm."""

    def getFields(self, *args):
        """Add the extra grade field's value from survey_record."""
        if hasattr(self.survey_record, 'grade'):
            grade = self.survey_record.grade
        vals_grade = {True: 'pass', False: 'fail'}
        self.data['grade'] = vals_grade.get(grade, None) or grade
        return super(GradeSurveyRecordForm, self).getFields(*args)

    def insertFields(self):
        """Add ordered fields to self.fields, add grade field with grade choices."""
        fields = super(GradeSurveyRecordForm, self).insertFields()
        grade_choices = (('', 'Choose a Grade'),) + tuple(DEF_GRADE_CHOICES)
        gradeField = forms.fields.CharField(widget=custom_widgets.PlainTextWidget, initial=self.data.get('grade'))
        fields.insert(len(fields) + 1, 'grade', gradeField)
        return fields


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

Class description:
Metaclass for changing the :meth:GPG.__init__ initialiser. Detects running gpg-agent processes and the presence of a pinentry program, and disables pinentry so that python-gnupg can write the passphrase to the controlled GnuPG process without killing the agent. :attr _agent_proc: If a :program:`gpg-agent` process is currently running for the effective userid, then **_agent_proc** will be set to a ``psutil.Process`` for that process.

Method signatures and docstrings:
- def __new__(cls, name, bases, attrs): Construct the initialiser for GPG
- def _find_agent(cls): Discover if a gpg-agent process for the current euid is running. If there is a matching gpg-agent process, set a :class:`psutil.Process` instance containing the gpg-agent process' information to ``cls._agent_proc``. For Unix systems, we check that the effective UID of this ``python-gnupg`` process is also the owner of the gpg-agent process. For Windows, we check that the usernames of the owners are the same. (Sorry Windows users; maybe you should switch to anything else.) .. note: This function will only run if the psutil_ Python extension is installed. Because psutil won't run with the PyPy interpreter, use of it is optional (although highly recommended). .. _psutil: https://pypi.python.org

Implement the Python class `GPGMeta` described below.

Class description:
Metaclass for changing the :meth:GPG.__init__ initialiser. Detects running gpg-agent processes and the presence of a pinentry program, and disables pinentry so that python-gnupg can write the passphrase to the controlled GnuPG process without killing the agent. :attr _agent_proc: If a :program:`gpg-agent` process is currently running for the effective userid, then **_agent_proc** will be set to a ``psutil.Process`` for that process.

Method signatures and docstrings:
- def __new__(cls, name, bases, attrs): Construct the initialiser for GPG
- def _find_agent(cls): Discover if a gpg-agent process for the current euid is running. If there is a matching gpg-agent process, set a :class:`psutil.Process` instance containing the gpg-agent process' information to ``cls._agent_proc``. For Unix systems, we check that the effective UID of this ``python-gnupg`` process is also the owner of the gpg-agent process. For Windows, we check that the usernames of the owners are the same. (Sorry Windows users; maybe you should switch to anything else.) .. note: This function will only run if the psutil_ Python extension is installed. Because psutil won't run with the PyPy interpreter, use of it is optional (although highly recommended). .. _psutil: https://pypi.python.org

<|skeleton|>
class GPGMeta:
    """Metaclass for changing the :meth:GPG.__init__ initialiser. Detects running gpg-agent processes and the presence of a pinentry program, and disables pinentry so that python-gnupg can write the passphrase to the controlled GnuPG process without killing the agent. :attr _agent_proc: If a :program:`gpg-agent` process is currently running for the effective userid, then **_agent_proc** will be set to a ``psutil.Process`` for that process."""

    def __new__(cls, name, bases, attrs):
        """Construct the initialiser for GPG"""
        <|body_0|>

    def _find_agent(cls):
        """Discover if a gpg-agent process for the current euid is running. If there is a matching gpg-agent process, set a :class:`psutil.Process` instance containing the gpg-agent process' information to ``cls._agent_proc``. For Unix systems, we check that the effective UID of this ``python-gnupg`` process is also the owner of the gpg-agent process. For Windows, we check that the usernames of the owners are the same. (Sorry Windows users; maybe you should switch to anything else.) .. note: This function will only run if the psutil_ Python extension is installed. Because psutil won't run with the PyPy interpreter, use of it is optional (although highly recommended). .. _psutil: https://pypi.python.org"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        log.debug('Metaclass __new__ constructor called for %r' % cls)
        if cls._find_agent():
            attrs['init'] = cls.__init__
            attrs['_remove_agent'] = True
        return super(GPGMeta, cls).__new__(cls, name, bases, attrs)
<|end_body_0|>

<|body_start_1|>
        if not psutil:
            return False
        this_process = psutil.Process(os.getpid())
        ownership_match = False
        if _util._running_windows:
            identity = this_process.username()
        else:
            identity = this_process.uids
        for proc in psutil.process_iter():
            if proc.name == 'gpg-agent' and proc.is_running:
                log.debug('Found gpg-agent process with pid %d' % proc.pid)
                if _util._running_windows:
                    if proc.username() == identity:
                        ownership_match = True
                elif proc.uids == identity:
                    ownership_match = True
        if ownership_match:
            log.debug('Effective UIDs of this process and gpg-agent match')
            setattr(cls, '_agent_proc', proc)
            return True
        return False
<|end_body_1|>

Solution:
class GPGMeta:
    """Metaclass for changing the :meth:GPG.__init__ initialiser. Detects running gpg-agent processes and the presence of a pinentry program, and disables pinentry so that python-gnupg can write the passphrase to the controlled GnuPG process without killing the agent. :attr _agent_proc: If a :program:`gpg-agent` process is currently running for the effective userid, then **_agent_proc** will be set to a ``psutil.Process`` for that process."""

    def __new__(cls, name, bases, attrs):
        """Construct the initialiser for GPG"""
        log.debug('Metaclass __new__ constructor called for %r' % cls)
        if cls._find_agent():
            attrs['init'] = cls.__init__
            attrs['_remove_agent'] = True
        return super(GPGMeta, cls).__new__(cls, name, bases, attrs)

    def _find_agent(cls):
        """Discover if a gpg-agent process for the current euid is running. If there is a matching gpg-agent process, set a :class:`psutil.Process` instance containing the gpg-agent process' information to ``cls._agent_proc``. For Unix systems, we check that the effective UID of this ``python-gnupg`` process is also the owner of the gpg-agent process. For Windows, we check that the usernames of the owners are the same. (Sorry Windows users; maybe you should switch to anything else.) .. note: This function will only run if the psutil_ Python extension is installed. Because psutil won't run with the PyPy interpreter, use of it is optional (although highly recommended). .. _psutil: https://pypi.python.org"""
        if not psutil:
            return False
        this_process = psutil.Process(os.getpid())
        ownership_match = False
        if _util._running_windows:
            identity = this_process.username()
        else:
            identity = this_process.uids
        for proc in psutil.process_iter():
            if proc.name == 'gpg-agent' and proc.is_running:
                log.debug('Found gpg-agent process with pid %d' % proc.pid)
                if _util._running_windows:
                    if proc.username() == identity:
                        ownership_match = True
                elif proc.uids == identity:
                    ownership_match = True
        if ownership_match:
            log.debug('Effective UIDs of this process and gpg-agent match')
            setattr(cls, '_agent_proc', proc)
            return True
        return False


deserialize

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

Class description:
Implement the Codec class.

Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: List[TreeNode]
- def deserialize(self, data): Decodes your encoded data to tree. :type data: List[TreeNode] :rtype: TreeNode

Implement the Python class `Codec` described below.

Class description:
Implement the Codec class.

Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: List[TreeNode]
- def deserialize(self, data): Decodes your encoded data to tree. :type data: List[TreeNode] :rtype: TreeNode

<|skeleton|>
class Codec:

    def serialize(self, root):
        """Encodes a tree to a single string. :type root: TreeNode :rtype: List[TreeNode]"""
        <|body_0|>

    def deserialize(self, data):
        """Decodes your encoded data to tree. :type data: List[TreeNode] :rtype: TreeNode"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        if root == None:
            return []
        queue = [root]
        data = []
        while queue:
            node = queue.pop(0)
            if node != None:
                data.append(node.val)
                queue.append(node.left)
                queue.append(node.right)
            else:
                data.append(None)
        return data
<|end_body_0|>

<|body_start_1|>
        if not data:
            return None
        root = TreeNode(data.pop(0))
        queue = [root]
        index = 0
        while queue:
            node = queue.pop(0)
            left = data[index]
            index += 1
            right = data[index]
            index += 1
            if left != None:
                lNode = TreeNode(left)
                queue.append(lNode)
                node.left = lNode
            else:
                node.left = None
            if right != None:
                rNode = TreeNode(right)
                queue.append(rNode)
                node.right = rNode
            else:
                node.right = None
        return root
<|end_body_1|>

Solution:
class Codec:
    def serialize(self, root):
        """Encodes a tree to a single string. :type root: TreeNode :rtype: List[TreeNode]"""
        if root == None:
            return []
        queue = [root]
        data = []
        while queue:
            node = queue.pop(0)
            if node != None:
                data.append(node.val)
                queue.append(node.left)
                queue.append(node.right)
            else:
                data.append(None)
        return data

    def deserialize(self, data):
        """Decodes your encoded data to tree. :type data: List[TreeNode] :rtype: TreeNode"""
        if not data:
            return None
        root = TreeNode(data.pop(0))
        queue = [root]
        index = 0
        while queue:
            node = queue.pop(0)
            left = data[index]
            index += 1
            right = data[index]
            index += 1
            if left != None:
                lNode = TreeNode(left)
                queue.append(lNode)
                node.left = lNode
            else:
                node.left = None
            if right != None:
                rNode = TreeNode(right)
                queue.append(rNode)
                node.right = rNode
            else:
                node.right = None
        return root


update

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

Class description:
A chef which moves left and right, dropping pizzas.

Method signatures and docstrings:
- def __init__(self, y=55, speed=2, odds_change=200): Initialize the Chef object.
- def update(self): Determine if direction needs to be reversed.
- def check_drop(self): Decrease countdown or drop pizza and reset countdown.

Implement the Python class `Chef` described below.

Class description:
A chef which moves left and right, dropping pizzas.

Method signatures and docstrings:
- def __init__(self, y=55, speed=2, odds_change=200): Initialize the Chef object.
- def update(self): Determine if direction needs to be reversed.
- def check_drop(self): Decrease countdown or drop pizza and reset countdown.

<|skeleton|>
class Chef:
    """A chef which moves left and right, dropping pizzas."""

    def __init__(self, y=55, speed=2, odds_change=200):
        """Initialize the Chef object."""
        <|body_0|>

    def update(self):
        """Determine if direction needs to be reversed."""
        <|body_1|>

    def check_drop(self):
        """Decrease countdown or drop pizza and reset countdown."""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        super(Chef, self).__init__(image=Chef.image, x=games.screen.width / 2, y=y, dx=speed)
        self.odds_change = odds_change
        self.time_til_drop = 0
<|end_body_0|>

<|body_start_1|>
        if self.left < 0 or self.right > games.screen.width:
            self.dx = -self.dx
        elif random.randrange(self.odds_change) == 0:
            self.dx = -self.dx
        self.check_drop()
<|end_body_1|>

<|body_start_2|>
        if self.time_til_drop > 0:
            self.time_til_drop -= 1
        else:
            new_pizza = Pizza(x=self.x)
            games.screen.add(new_pizza)
            self.time_til_drop = int(new_pizza.height * 1.3 / Pizza.speed) + 1
<|end_body_2|>

Solution:
class Chef:
    """A chef which moves left and right, dropping pizzas."""

    def __init__(self, y=55, speed=2, odds_change=200):
        """Initialize the Chef object."""
        super(Chef, self).__init__(image=Chef.image, x=games.screen.width / 2, y=y, dx=speed)
        self.odds_change = odds_change
        self.time_til_drop = 0

    def update(self):
        """Determine if direction needs to be reversed."""
        if self.left < 0 or self.right > games.screen.width:
            self.dx = -self.dx
        elif random.randrange(self.odds_change) == 0:
            self.dx = -self.dx
        self.check_drop()

    def check_drop(self):
        """Decrease countdown or drop pizza and reset countdown."""
        if self.time_til_drop > 0:
            self.time_til_drop -= 1
        else:
            new_pizza = Pizza(x=self.x)
            games.screen.add(new_pizza)
            self.time_til_drop = int(new_pizza.height * 1.3 / Pizza.speed) + 1


forward

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

Class description:
Implement the ProductNodes class.

Method signatures and docstrings:
- def __init__(self, is_cuda, num=1): :param is_cuda: determines if the node is stored on the gpu or cpu :param num: The number of nodes being created
- def forward(self): Overriding torch's forward pass for Product nodes.

Implement the Python class `ProductNodes` described below.

Class description:
Implement the ProductNodes class.

Method signatures and docstrings:
- def __init__(self, is_cuda, num=1): :param is_cuda: determines if the node is stored on the gpu or cpu :param num: The number of nodes being created
- def forward(self): Overriding torch's forward pass for Product nodes.

<|skeleton|>
class ProductNodes:

    def __init__(self, is_cuda, num=1):
        """:param is_cuda: determines if the node is stored on the gpu or cpu :param num: The number of nodes being created"""
        <|body_0|>

    def forward(self):
        """Overriding torch's forward pass for Product nodes."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        Nodes.__init__(self, is_cuda).__init__()
        self.num = num
        self.is_cuda = is_cuda
        self.child_edges = []
        self.parent_edges = []
        self.val = None
<|end_body_0|>

<|body_start_1|>
        batch = self.child_edges[0].child.val.size()[0]
        self.val = self.var(torch.zeros((batch, self.num)))
        for e in self.child_edges:
            self.val += torch.mm(e.child.val, e.connections)
        return self.val
<|end_body_1|>

Solution:
class ProductNodes:
    def __init__(self, is_cuda, num=1):
        """:param is_cuda: determines if the node is stored on the gpu or cpu :param num: The number of nodes being created"""
        Nodes.__init__(self, is_cuda).__init__()
        self.num = num
        self.is_cuda = is_cuda
        self.child_edges = []
        self.parent_edges = []
        self.val = None

    def forward(self):
        """Overriding torch's forward pass for Product nodes."""
        batch = self.child_edges[0].child.val.size()[0]
        self.val = self.var(torch.zeros((batch, self.num)))
        for e in self.child_edges:
            self.val += torch.mm(e.child.val, e.connections)
        return self.val


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

Class description:
Implement the TestExamples class.

Method signatures and docstrings:
- def test_eg1(self): Test specific fields
- def test_eg2(self): Test entire example 2
- def test_eg3(self): Test outputing error when weights are incorrect

Implement the Python class `TestExamples` described below.

Class description:
Implement the TestExamples class.

Method signatures and docstrings:
- def test_eg1(self): Test specific fields
- def test_eg2(self): Test entire example 2
- def test_eg3(self): Test outputing error when weights are incorrect

<|skeleton|>
class TestExamples:

    def test_eg1(self):
        """Test specific fields"""
        <|body_0|>

    def test_eg2(self):
        """Test entire example 2"""
        <|body_1|>

    def test_eg3(self):
        """Test outputing error when weights are incorrect"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        ex_dir = './Example1/{}'
        ex_files = ['courses.csv', 'students.csv', 'tests.csv', 'marks.csv', 'output_test.json']
        sol = Solution([ex_dir.format(s) for s in ex_files])
        sol.writing()
        with open(ex_dir.format(ex_files[-1])) as f:
            res = json.load(f)
        with open(ex_dir.format('output.json')) as f:
            expected_res = json.load(f)
        self.assertEqual(res['students'][1]['totalAverage'], expected_res['students'][1]['totalAverage'])
        self.assertEqual(res['students'][1]['courses'], expected_res['students'][1]['courses'])
<|end_body_0|>

<|body_start_1|>
        ex_dir = './Example2/{}'
        ex_files = ['courses.csv', 'students.csv', 'tests.csv', 'marks.csv', 'output_test.json']
        sol = Solution([ex_dir.format(s) for s in ex_files])
        sol.writing()
        with open(ex_dir.format(ex_files[-1])) as f:
            res = json.load(f)
        with open(ex_dir.format('output.json')) as f:
            expected_res = json.load(f)
        self.assertEqual(res, expected_res)
<|end_body_1|>

<|body_start_2|>
        ex_dir = './Example3/{}'
        ex_files = ['courses.csv', 'students.csv', 'tests.csv', 'marks.csv', 'output_test.json']
        sol = Solution([ex_dir.format(s) for s in ex_files])
        sol.writing()
        with open(ex_dir.format(ex_files[-1])) as f:
            res = json.load(f)
        self.assertEqual(res, {'error': 'Invalid course weights'})
<|end_body_2|>

Solution:
class TestExamples:
    def test_eg1(self):
        """Test specific fields"""
        ex_dir = './Example1/{}'
        ex_files = ['courses.csv', 'students.csv', 'tests.csv', 'marks.csv', 'output_test.json']
        sol = Solution([ex_dir.format(s) for s in ex_files])
        sol.writing()
        with open(ex_dir.format(ex_files[-1])) as f:
            res = json.load(f)
        with open(ex_dir.format('output.json')) as f:
            expected_res = json.load(f)
        self.assertEqual(res['students'][1]['totalAverage'], expected_res['students'][1]['totalAverage'])
        self.assertEqual(res['students'][1]['courses'], expected_res['students'][1]['courses'])

    def test_eg2(self):
        """Test entire example 2"""
        ex_dir = './Example2/{}'
        ex_files = ['courses.csv', 'students.csv', 'tests.csv', 'marks.csv', 'output_test.json']
        sol = Solution([ex_dir.format(s) for s in ex_files])
        sol.writing()
        with open(ex_dir.format(ex_files[-1])) as f:
            res = json.load(f)
        with open(ex_dir.format('output.json')) as f:
            expected_res = json.load(f)
        self.assertEqual(res, expected_res)

    def test_eg3(self):
        """Test outputing error when weights are incorrect"""
        ex_dir = './Example3/{}'
        ex_files = ['courses.csv', 'students.csv', 'tests.csv', 'marks.csv', 'output_test.json']
        sol = Solution([ex_dir.format(s) for s in ex_files])
        sol.writing()
        with open(ex_dir.format(ex_files[-1])) as f:
            res = json.load(f)
        self.assertEqual(res, {'error': 'Invalid course weights'})


create

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

Class description:
This view is the endpoint for retrieving the list of all Scan process.

Method signatures and docstrings:
- def get_serializer_class(self): Returns the appropriate serializer based off the requests version of the REST API.
- def list(self, request): Retrieves the list of all Scan process and returns it in JSON form :param request: the HTTP GET request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user
- def _list_v6(self, request): Retrieves the list of all Scan process and returns it in JSON form :param request: the HTTP GET request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user
- def create(self, request): Creates a new Scan process and returns a link to the detail URL :param request: the HTTP POST request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user
- def _create_v6(self, request): Creates a new Scan process and returns a link to the detail URL :param request: the HTTP POST request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user

Implement the Python class `ScansView` described below.

Class description:
This view is the endpoint for retrieving the list of all Scan process.

Method signatures and docstrings:
- def get_serializer_class(self): Returns the appropriate serializer based off the requests version of the REST API.
- def list(self, request): Retrieves the list of all Scan process and returns it in JSON form :param request: the HTTP GET request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user
- def _list_v6(self, request): Retrieves the list of all Scan process and returns it in JSON form :param request: the HTTP GET request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user
- def create(self, request): Creates a new Scan process and returns a link to the detail URL :param request: the HTTP POST request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user
- def _create_v6(self, request): Creates a new Scan process and returns a link to the detail URL :param request: the HTTP POST request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user

<|skeleton|>
class ScansView:
    """This view is the endpoint for retrieving the list of all Scan process."""

    def get_serializer_class(self):
        """Returns the appropriate serializer based off the requests version of the REST API."""
        <|body_0|>

    def list(self, request):
        """Retrieves the list of all Scan process and returns it in JSON form :param request: the HTTP GET request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user"""
        <|body_1|>

    def _list_v6(self, request):
        """Retrieves the list of all Scan process and returns it in JSON form :param request: the HTTP GET request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user"""
        <|body_2|>

    def create(self, request):
        """Creates a new Scan process and returns a link to the detail URL :param request: the HTTP POST request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user"""
        <|body_3|>

    def _create_v6(self, request):
        """Creates a new Scan process and returns a link to the detail URL :param request: the HTTP POST request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user"""
        <|body_4|>

<|end_skeleton|>

<|body_start_0|>
        if self.request.version == 'v6':
            return ScanSerializerV6
        elif self.request.version == 'v7':
            return ScanSerializerV6
<|end_body_0|>

<|body_start_1|>
        if request.version == 'v6':
            return self._list_v6(request)
        elif request.version == 'v7':
            return self._list_v6(request)
        raise Http404()
<|end_body_1|>

<|body_start_2|>
        started = rest_util.parse_timestamp(request, 'started', required=False)
        ended = rest_util.parse_timestamp(request, 'ended', required=False)
        rest_util.check_time_range(started, ended)
        names = rest_util.parse_string_list(request, 'name', required=False)
        order = rest_util.parse_string_list(request, 'order', required=False)
        scans = Scan.objects.get_scans(started, ended, names, order)
        page = self.paginate_queryset(scans)
        serializer = self.get_serializer(page, many=True)
        return self.get_paginated_response(serializer.data)
<|end_body_2|>

<|body_start_3|>
        if request.version == 'v6':
            return self._create_v6(request)
        elif request.version == 'v7':
            return self._create_v6(request)
        raise Http404()
<|end_body_3|>

<|body_start_4|>
        title = rest_util.parse_string(request, 'title', required=True)
        name = title_to_name(self.queryset, title)
        description = rest_util.parse_string(request, 'description', required=False)
        configuration = rest_util.parse_dict(request, 'configuration')
        try:
            config = ScanConfigurationV6(configuration, do_validate=True).get_configuration()
        except InvalidScanConfiguration as ex:
            raise BadParameter('Scan configuration invalid: %s' % unicode(ex))
        try:
            scan = Scan.objects.create_scan(name, title, description, config)
        except InvalidScanConfiguration as ex:
            raise BadParameter('Scan configuration invalid: %s' % unicode(ex))
        serializer = ScanDetailsSerializerV6(scan)
        scan_url = reverse('scans_details_view', args=[scan.id], request=request)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=dict(location=scan_url))
<|end_body_4|>

Solution:
class ScansView:
    """This view is the endpoint for retrieving the list of all Scan process."""

    def get_serializer_class(self):
        """Returns the appropriate serializer based off the requests version of the REST API."""
        if self.request.version == 'v6':
            return ScanSerializerV6
        elif self.request.version == 'v7':
            return ScanSerializerV6

    def list(self, request):
        """Retrieves the list of all Scan process and returns it in JSON form :param request: the HTTP GET request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user"""
        if request.version == 'v6':
            return self._list_v6(request)
        elif request.version == 'v7':
            return self._list_v6(request)
        raise Http404()

    def _list_v6(self, request):
        """Retrieves the list of all Scan process and returns it in JSON form :param request: the HTTP GET request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user"""
        started = rest_util.parse_timestamp(request, 'started', required=False)
        ended = rest_util.parse_timestamp(request, 'ended', required=False)
        rest_util.check_time_range(started, ended)
        names = rest_util.parse_string_list(request, 'name', required=False)
        order = rest_util.parse_string_list(request, 'order', required=False)
        scans = Scan.objects.get_scans(started, ended, names, order)
        page = self.paginate_queryset(scans)
        serializer = self.get_serializer(page, many=True)
        return self.get_paginated_response(serializer.data)

    def create(self, request):
        """Creates a new Scan process and returns a link to the detail URL :param request: the HTTP POST request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user"""
        if request.version == 'v6':
            return self._create_v6(request)
        elif request.version == 'v7':
            return self._create_v6(request)
        raise Http404()

    def _create_v6(self, request):
        """Creates a new Scan process and returns a link to the detail URL :param request: the HTTP POST request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user"""
        title = rest_util.parse_string(request, 'title', required=True)
        name = title_to_name(self.queryset, title)
        description = rest_util.parse_string(request, 'description', required=False)
        configuration = rest_util.parse_dict(request, 'configuration')
        try:
            config = ScanConfigurationV6(configuration, do_validate=True).get_configuration()
        except InvalidScanConfiguration as ex:
            raise BadParameter('Scan configuration invalid: %s' % unicode(ex))
        try:
            scan = Scan.objects.create_scan(name, title, description, config)
        except InvalidScanConfiguration as ex:
            raise BadParameter('Scan configuration invalid: %s' % unicode(ex))
        serializer = ScanDetailsSerializerV6(scan)
        scan_url = reverse('scans_details_view', args=[scan.id], request=request)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=dict(location=scan_url))


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

Class description:
Base-class for SettingsRoot screen.

Method signatures and docstrings:
- def add_section(self, section_name: str): Add section by name. Must be contained in :attr:`cookbook`.
- def on_config(self, *_): Add add sections from :attr:`config`.

Implement the Python class `SettingsWidget` described below.

Class description:
Base-class for SettingsRoot screen.

Method signatures and docstrings:
- def add_section(self, section_name: str): Add section by name. Must be contained in :attr:`cookbook`.
- def on_config(self, *_): Add add sections from :attr:`config`.

<|skeleton|>
class SettingsWidget:
    """Base-class for SettingsRoot screen."""

    def add_section(self, section_name: str):
        """Add section by name. Must be contained in :attr:`cookbook`."""
        <|body_0|>

    def on_config(self, *_):
        """Add add sections from :attr:`config`."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        section = self.cookbook.cook(section_name, config=self.config)
        self.sections[section_name] = section
        self.add_widget(SeparatorWithHeading(heading=section_name))
        self.add_widget(section)
<|end_body_0|>

<|body_start_1|>
        for section_name in self.config:
            if section_name in self.cookbook.get_recipe_names():
                self.add_section(section_name)
<|end_body_1|>

Solution:
class SettingsWidget:
    """Base-class for SettingsRoot screen."""

    def add_section(self, section_name: str):
        """Add section by name. Must be contained in :attr:`cookbook`."""
        section = self.cookbook.cook(section_name, config=self.config)
        self.sections[section_name] = section
        self.add_widget(SeparatorWithHeading(heading=section_name))
        self.add_widget(section)

    def on_config(self, *_):
        """Add add sections from :attr:`config`."""
        for section_name in self.config:
            if section_name in self.cookbook.get_recipe_names():
                self.add_section(section_name)


合作商购买有限注册提交资料

合作商购买有限合伙注册提交资料

合作商购买个人独资注册提交资料

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

Class description:
Implement the HeRegister class.

Method signatures and docstrings:
- def test_case01(self): 合作商购买有限注册提交资料
- def test_case02(self): 合作商购买有限合伙注册提交资料
- def test_case03(self): 合作商购买个人独资注册提交资料

Implement the Python class `HeRegister` described below.

Class description:
Implement the HeRegister class.

Method signatures and docstrings:
- def test_case01(self): 合作商购买有限注册提交资料
- def test_case02(self): 合作商购买有限合伙注册提交资料
- def test_case03(self): 合作商购买个人独资注册提交资料

<|skeleton|>
class HeRegister:

    def test_case01(self):
        """合作商购买有限注册提交资料"""
        <|body_0|>

    def test_case02(self):
        """合作商购买有限合伙注册提交资料"""
        <|body_1|>

    def test_case03(self):
        """合作商购买个人独资注册提交资料"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        self.helimited_company_submitting_information()
        actual = self.driver.find_element_by_class_name('el-input__inner').is_enabled()
        self.assertTrue(actual)
        logger.info('断言')
<|end_body_0|>

<|body_start_1|>
        self.helimited_partnership_submission()
        actual = self.driver.find_element_by_class_name('el-input__inner').is_enabled()
        self.assertTrue(actual)
        logger.info('断言')
<|end_body_1|>

<|body_start_2|>
        self.hesole_proprietorship_submission()
        actual = self.driver.find_element_by_class_name('el-input__inner').is_enabled()
        self.assertTrue(actual)
        logger.info('断言')
<|end_body_2|>

Solution:
class HeRegister:
    def test_case01(self):
        """合作商购买有限注册提交资料"""
        self.helimited_company_submitting_information()
        actual = self.driver.find_element_by_class_name('el-input__inner').is_enabled()
        self.assertTrue(actual)
        logger.info('断言')

    def test_case02(self):
        """合作商购买有限合伙注册提交资料"""
        self.helimited_partnership_submission()
        actual = self.driver.find_element_by_class_name('el-input__inner').is_enabled()
        self.assertTrue(actual)
        logger.info('断言')

    def test_case03(self):
        """合作商购买个人独资注册提交资料"""
        self.hesole_proprietorship_submission()
        actual = self.driver.find_element_by_class_name('el-input__inner').is_enabled()
        self.assertTrue(actual)
        logger.info('断言')