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

Class description:
Representa una búsqueda de entidades territoriales (provincias, departamentos, etc.). Attributes: _geo_shape_ids (dict): Diccionario de str - list, las keys siendo tipos de entidades, y los valores siendo listas de IDs para el tipo de entidad. Se separa este atributo de los parámetros de búsqueda ya que requiere un manejo especial (requiere realizar consultas adicionales a otros índices). _geom_search_class (type): Clase que debería utilizarse para buscar geometrías para entidades de este TerritoriesSearch. Si es 'None', las geometrías simplemente pueden ser obtenidas agregando 'geometria' a la lista de campos. _fetch_geoms (bool): Verdadero si es necesario realizar consultas adicionales par

Method signatures and docstrings:
- def __init__(self, index, query, geom_search_class=None): Inicializa un objeto de tipo TerritoriesSearch. Args: index (str): Ver atributo '_index'. query (dict): Parámetros de la búsqueda. Ver el método '_read_query' para tomar nota de los valores permitidos dentro del diccionario. geom_search_class (type): Ver atributo '_geom_search_class'.
- def _read_query(self, ids=None, name=None, census_locality=None, municipality=None, department=None, state=None, exact=False, geo_shape_geoms=None, order=None, **kwargs): Lee los parámetros de búsqueda recibidos y los agrega al atributo 'self._search'. Luego, invoca al método '_read_query' de la superclase con los parámetros que no fueron procesados. Args: ids (list): Filtrar por IDs de entidades. name (str): Filtrar por nombre de entidades. census_locality (list, str): Filtrar por nombre o IDs de localidades censales. municipality (list, str): Filtrar por nombre o IDs de municipios. department (list, str): Filtrar por nombre o IDs de departamentos. state (list, str): Filtrar por nombre o IDs de provincias. exact (bool): Si es verdadero, desactivar la búsqueda fuzzy para todos los parámetros de texto siendo utilizados (nombre, provincia, etc.). geo_shape_geom
- def search_steps(self): Ver documentación de 'ElasticsearchSearch.search_steps'. Pasos requeridos: 1) Expandir parámetros 'geo_shape_ids'. (opcional) 2) Buscar la entidad principal. 3) Obtener geometrías. (opcional)

Implement the Python class `TerritoriesSearch` described below.

Class description:
Representa una búsqueda de entidades territoriales (provincias, departamentos, etc.). Attributes: _geo_shape_ids (dict): Diccionario de str - list, las keys siendo tipos de entidades, y los valores siendo listas de IDs para el tipo de entidad. Se separa este atributo de los parámetros de búsqueda ya que requiere un manejo especial (requiere realizar consultas adicionales a otros índices). _geom_search_class (type): Clase que debería utilizarse para buscar geometrías para entidades de este TerritoriesSearch. Si es 'None', las geometrías simplemente pueden ser obtenidas agregando 'geometria' a la lista de campos. _fetch_geoms (bool): Verdadero si es necesario realizar consultas adicionales par

Method signatures and docstrings:
- def __init__(self, index, query, geom_search_class=None): Inicializa un objeto de tipo TerritoriesSearch. Args: index (str): Ver atributo '_index'. query (dict): Parámetros de la búsqueda. Ver el método '_read_query' para tomar nota de los valores permitidos dentro del diccionario. geom_search_class (type): Ver atributo '_geom_search_class'.
- def _read_query(self, ids=None, name=None, census_locality=None, municipality=None, department=None, state=None, exact=False, geo_shape_geoms=None, order=None, **kwargs): Lee los parámetros de búsqueda recibidos y los agrega al atributo 'self._search'. Luego, invoca al método '_read_query' de la superclase con los parámetros que no fueron procesados. Args: ids (list): Filtrar por IDs de entidades. name (str): Filtrar por nombre de entidades. census_locality (list, str): Filtrar por nombre o IDs de localidades censales. municipality (list, str): Filtrar por nombre o IDs de municipios. department (list, str): Filtrar por nombre o IDs de departamentos. state (list, str): Filtrar por nombre o IDs de provincias. exact (bool): Si es verdadero, desactivar la búsqueda fuzzy para todos los parámetros de texto siendo utilizados (nombre, provincia, etc.). geo_shape_geom
- def search_steps(self): Ver documentación de 'ElasticsearchSearch.search_steps'. Pasos requeridos: 1) Expandir parámetros 'geo_shape_ids'. (opcional) 2) Buscar la entidad principal. 3) Obtener geometrías. (opcional)

<|skeleton|>
class TerritoriesSearch:
    """Representa una búsqueda de entidades territoriales (provincias, departamentos, etc.). Attributes: _geo_shape_ids (dict): Diccionario de str - list, las keys siendo tipos de entidades, y los valores siendo listas de IDs para el tipo de entidad. Se separa este atributo de los parámetros de búsqueda ya que requiere un manejo especial (requiere realizar consultas adicionales a otros índices). _geom_search_class (type): Clase que debería utilizarse para buscar geometrías para entidades de este TerritoriesSearch. Si es 'None', las geometrías simplemente pueden ser obtenidas agregando 'geometria' a la lista de campos. _fetch_geoms (bool): Verdadero si es necesario realizar consultas adicionales par"""

    def __init__(self, index, query, geom_search_class=None):
        """Inicializa un objeto de tipo TerritoriesSearch. Args: index (str): Ver atributo '_index'. query (dict): Parámetros de la búsqueda. Ver el método '_read_query' para tomar nota de los valores permitidos dentro del diccionario. geom_search_class (type): Ver atributo '_geom_search_class'."""
        <|body_0|>

    def _read_query(self, ids=None, name=None, census_locality=None, municipality=None, department=None, state=None, exact=False, geo_shape_geoms=None, order=None, **kwargs):
        """Lee los parámetros de búsqueda recibidos y los agrega al atributo 'self._search'. Luego, invoca al método '_read_query' de la superclase con los parámetros que no fueron procesados. Args: ids (list): Filtrar por IDs de entidades. name (str): Filtrar por nombre de entidades. census_locality (list, str): Filtrar por nombre o IDs de localidades censales. municipality (list, str): Filtrar por nombre o IDs de municipios. department (list, str): Filtrar por nombre o IDs de departamentos. state (list, str): Filtrar por nombre o IDs de provincias. exact (bool): Si es verdadero, desactivar la búsqueda fuzzy para todos los parámetros de texto siendo utilizados (nombre, provincia, etc.). geo_shape_geom"""
        <|body_1|>

    def search_steps(self):
        """Ver documentación de 'ElasticsearchSearch.search_steps'. Pasos requeridos: 1) Expandir parámetros 'geo_shape_ids'. (opcional) 2) Buscar la entidad principal. 3) Obtener geometrías. (opcional)"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        self._geo_shape_ids = query.pop('geo_shape_ids', None)
        self._geom_search_class = geom_search_class
        fields = query.get('fields')
        if fields and self._geom_search_class:
            self._fetch_geoms = N.GEOM in fields and N.ID in fields
        else:
            self._fetch_geoms = False
        super().__init__(index, query)
<|end_body_0|>

<|body_start_1|>
        super()._read_query(**kwargs)
        if ids:
            self._search = self._search.filter(_build_terms_query(N.ID, ids))
        if name:
            self._search = self._search.query(_build_name_query(N.NAME, name, exact))
        if geo_shape_geoms:
            self._search = self._search.query(_build_geo_query(N.GEOM, geoms=geo_shape_geoms))
        if census_locality:
            self._search = self._search.query(_build_subentity_query(N.CENSUS_LOCALITY_ID, N.CENSUS_LOCALITY_NAME, census_locality, exact))
        if municipality:
            self._search = self._search.query(_build_subentity_query(N.MUN_ID, N.MUN_NAME, municipality, exact))
        if department:
            self._search = self._search.query(_build_subentity_query(N.DEPT_ID, N.DEPT_NAME, department, exact))
        if state:
            self._search = self._search.query(_build_subentity_query(N.STATE_ID, N.STATE_NAME, state, exact))
        if order:
            if order == N.NAME:
                order = N.EXACT_SUFFIX.format(order)
            self._search = self._search.sort(order)
<|end_body_1|>

<|body_start_2|>
        if self._geo_shape_ids:
            yield from self._expand_intersection_query(self._geo_shape_ids)
        response = (yield self._search)
        self._result = ElasticsearchResult(response, self._offset)
        if self._fetch_geoms:
            yield from self._expand_geometry_query(self._geom_search_class)
<|end_body_2|>

Solution:
class TerritoriesSearch:
    """Representa una búsqueda de entidades territoriales (provincias, departamentos, etc.). Attributes: _geo_shape_ids (dict): Diccionario de str - list, las keys siendo tipos de entidades, y los valores siendo listas de IDs para el tipo de entidad. Se separa este atributo de los parámetros de búsqueda ya que requiere un manejo especial (requiere realizar consultas adicionales a otros índices). _geom_search_class (type): Clase que debería utilizarse para buscar geometrías para entidades de este TerritoriesSearch. Si es 'None', las geometrías simplemente pueden ser obtenidas agregando 'geometria' a la lista de campos. _fetch_geoms (bool): Verdadero si es necesario realizar consultas adicionales par"""

    def __init__(self, index, query, geom_search_class=None):
        """Inicializa un objeto de tipo TerritoriesSearch. Args: index (str): Ver atributo '_index'. query (dict): Parámetros de la búsqueda. Ver el método '_read_query' para tomar nota de los valores permitidos dentro del diccionario. geom_search_class (type): Ver atributo '_geom_search_class'."""
        self._geo_shape_ids = query.pop('geo_shape_ids', None)
        self._geom_search_class = geom_search_class
        fields = query.get('fields')
        if fields and self._geom_search_class:
            self._fetch_geoms = N.GEOM in fields and N.ID in fields
        else:
            self._fetch_geoms = False
        super().__init__(index, query)

    def _read_query(self, ids=None, name=None, census_locality=None, municipality=None, department=None, state=None, exact=False, geo_shape_geoms=None, order=None, **kwargs):
        """Lee los parámetros de búsqueda recibidos y los agrega al atributo 'self._search'. Luego, invoca al método '_read_query' de la superclase con los parámetros que no fueron procesados. Args: ids (list): Filtrar por IDs de entidades. name (str): Filtrar por nombre de entidades. census_locality (list, str): Filtrar por nombre o IDs de localidades censales. municipality (list, str): Filtrar por nombre o IDs de municipios. department (list, str): Filtrar por nombre o IDs de departamentos. state (list, str): Filtrar por nombre o IDs de provincias. exact (bool): Si es verdadero, desactivar la búsqueda fuzzy para todos los parámetros de texto siendo utilizados (nombre, provincia, etc.). geo_shape_geom"""
        super()._read_query(**kwargs)
        if ids:
            self._search = self._search.filter(_build_terms_query(N.ID, ids))
        if name:
            self._search = self._search.query(_build_name_query(N.NAME, name, exact))
        if geo_shape_geoms:
            self._search = self._search.query(_build_geo_query(N.GEOM, geoms=geo_shape_geoms))
        if census_locality:
            self._search = self._search.query(_build_subentity_query(N.CENSUS_LOCALITY_ID, N.CENSUS_LOCALITY_NAME, census_locality, exact))
        if municipality:
            self._search = self._search.query(_build_subentity_query(N.MUN_ID, N.MUN_NAME, municipality, exact))
        if department:
            self._search = self._search.query(_build_subentity_query(N.DEPT_ID, N.DEPT_NAME, department, exact))
        if state:
            self._search = self._search.query(_build_subentity_query(N.STATE_ID, N.STATE_NAME, state, exact))
        if order:
            if order == N.NAME:
                order = N.EXACT_SUFFIX.format(order)
            self._search = self._search.sort(order)

    def search_steps(self):
        """Ver documentación de 'ElasticsearchSearch.search_steps'. Pasos requeridos: 1) Expandir parámetros 'geo_shape_ids'. (opcional) 2) Buscar la entidad principal. 3) Obtener geometrías. (opcional)"""
        if self._geo_shape_ids:
            yield from self._expand_intersection_query(self._geo_shape_ids)
        response = (yield self._search)
        self._result = ElasticsearchResult(response, self._offset)
        if self._fetch_geoms:
            yield from self._expand_geometry_query(self._geom_search_class)


grad

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

Class description:
Proxy object to evaluate loss function. f(p) = \\frac{\\lambda_{2}}{2 N_{px}}\\norm{\\bbB^{1/2} \\bbtau(p)}{2}^{2}

Method signatures and docstrings:
- def __init__(self, B, lambda_, p): Parameters ---------- B : :py:class:`~scipy.sparse.csr_matrix` (N_px, N_px) Graph Laplacian. lambda_ : float Regularization parameter >= 0. p : :py:class:`~deepwave.nn.crnn.Parameter` Serializer to encode/decode parameters.
- def eval(self, p, x): Evaluate f(p, x). Parameters ---------- p : :py:class:`~numpy.ndarray` (N_cell_1,) vectorized parameter encoding, output of :py:meth:`~deepwave.nn.crnn.Parameter.encode`. x : :py:class:`~numpy.ndarray` ([N_sample,], N_cell_2) vectorized sample encoding, output of :py:meth:`~deepwave.nn.Sampler.encode`. Several samples can be provided if stacked along axis 0. This variable is not used in the implementation, but is provided for interface consistency. Returns ------- z : float z = f(p)
- def grad(self, p, x): Evaluate \\grad_{p} f(p, x). Parameters ---------- p : :py:class:`~numpy.ndarray` (N_cell_1,) vectorized parameter encoding, output of :py:meth:`~deepwave.nn.crnn.Parameter.encode`. x : :py:class:`~numpy.ndarray` ([N_sample,], N_cell_2) vectorized sample encoding, output of :py:meth:`~deepwave.nn.Sampler.encode`. Several samples can be provided if stacked along axis 0. This variable is not used in the implementation, but is provided for interface consistency. Returns ------- z : :py:class:`~numpy.ndarray` (N_cell_1,) vectorized parameter gradient, output of :py:meth:`~deepwave.nn.crnn.Parameter.encode`. z = \\grad_{p}{f(p)}

Implement the Python class `LaplacianLossFunction` described below.

Class description:
Proxy object to evaluate loss function. f(p) = \\frac{\\lambda_{2}}{2 N_{px}}\\norm{\\bbB^{1/2} \\bbtau(p)}{2}^{2}

Method signatures and docstrings:
- def __init__(self, B, lambda_, p): Parameters ---------- B : :py:class:`~scipy.sparse.csr_matrix` (N_px, N_px) Graph Laplacian. lambda_ : float Regularization parameter >= 0. p : :py:class:`~deepwave.nn.crnn.Parameter` Serializer to encode/decode parameters.
- def eval(self, p, x): Evaluate f(p, x). Parameters ---------- p : :py:class:`~numpy.ndarray` (N_cell_1,) vectorized parameter encoding, output of :py:meth:`~deepwave.nn.crnn.Parameter.encode`. x : :py:class:`~numpy.ndarray` ([N_sample,], N_cell_2) vectorized sample encoding, output of :py:meth:`~deepwave.nn.Sampler.encode`. Several samples can be provided if stacked along axis 0. This variable is not used in the implementation, but is provided for interface consistency. Returns ------- z : float z = f(p)
- def grad(self, p, x): Evaluate \\grad_{p} f(p, x). Parameters ---------- p : :py:class:`~numpy.ndarray` (N_cell_1,) vectorized parameter encoding, output of :py:meth:`~deepwave.nn.crnn.Parameter.encode`. x : :py:class:`~numpy.ndarray` ([N_sample,], N_cell_2) vectorized sample encoding, output of :py:meth:`~deepwave.nn.Sampler.encode`. Several samples can be provided if stacked along axis 0. This variable is not used in the implementation, but is provided for interface consistency. Returns ------- z : :py:class:`~numpy.ndarray` (N_cell_1,) vectorized parameter gradient, output of :py:meth:`~deepwave.nn.crnn.Parameter.encode`. z = \\grad_{p}{f(p)}

<|skeleton|>
class LaplacianLossFunction:
    """Proxy object to evaluate loss function. f(p) = \\frac{\\lambda_{2}}{2 N_{px}}\\norm{\\bbB^{1/2} \\bbtau(p)}{2}^{2}"""

    def __init__(self, B, lambda_, p):
        """Parameters ---------- B : :py:class:`~scipy.sparse.csr_matrix` (N_px, N_px) Graph Laplacian. lambda_ : float Regularization parameter >= 0. p : :py:class:`~deepwave.nn.crnn.Parameter` Serializer to encode/decode parameters."""
        <|body_0|>

    def eval(self, p, x):
        """Evaluate f(p, x). Parameters ---------- p : :py:class:`~numpy.ndarray` (N_cell_1,) vectorized parameter encoding, output of :py:meth:`~deepwave.nn.crnn.Parameter.encode`. x : :py:class:`~numpy.ndarray` ([N_sample,], N_cell_2) vectorized sample encoding, output of :py:meth:`~deepwave.nn.Sampler.encode`. Several samples can be provided if stacked along axis 0. This variable is not used in the implementation, but is provided for interface consistency. Returns ------- z : float z = f(p)"""
        <|body_1|>

    def grad(self, p, x):
        """Evaluate \\grad_{p} f(p, x). Parameters ---------- p : :py:class:`~numpy.ndarray` (N_cell_1,) vectorized parameter encoding, output of :py:meth:`~deepwave.nn.crnn.Parameter.encode`. x : :py:class:`~numpy.ndarray` ([N_sample,], N_cell_2) vectorized sample encoding, output of :py:meth:`~deepwave.nn.Sampler.encode`. Several samples can be provided if stacked along axis 0. This variable is not used in the implementation, but is provided for interface consistency. Returns ------- z : :py:class:`~numpy.ndarray` (N_cell_1,) vectorized parameter gradient, output of :py:meth:`~deepwave.nn.crnn.Parameter.encode`. z = \\grad_{p}{f(p)}"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        super().__init__()
        if lambda_ < 0:
            raise ValueError('Parameter[lambda_] must be non-negative.')
        self._lambda_ = lambda_
        if not isinstance(B, sp.csr_matrix):
            raise ValueError('Parameter[B] must be (N_px, N_px) CSR.')
        self._B = B
        if not isinstance(p, Parameter):
            raise ValueError('Parameter[p]: expected deepwave.nn.crnn.Parameter')
        self._p = p
<|end_body_0|>

<|body_start_1|>
        _, _, tau = self._p.decode(p)
        N_px = tau.size
        z = 0.5 * self._lambda_ / N_px * (tau @ self._B.dot(tau))
        return z
<|end_body_1|>

<|body_start_2|>
        _, _, tau = self._p.decode(p)
        N_px = tau.size
        dtau = self._lambda_ / N_px * self._B.T.dot(tau)
        z = self._p.encode(tau=dtau)
        return z
<|end_body_2|>

Solution:
class LaplacianLossFunction:
    """Proxy object to evaluate loss function. f(p) = \\frac{\\lambda_{2}}{2 N_{px}}\\norm{\\bbB^{1/2} \\bbtau(p)}{2}^{2}"""

    def __init__(self, B, lambda_, p):
        """Parameters ---------- B : :py:class:`~scipy.sparse.csr_matrix` (N_px, N_px) Graph Laplacian. lambda_ : float Regularization parameter >= 0. p : :py:class:`~deepwave.nn.crnn.Parameter` Serializer to encode/decode parameters."""
        super().__init__()
        if lambda_ < 0:
            raise ValueError('Parameter[lambda_] must be non-negative.')
        self._lambda_ = lambda_
        if not isinstance(B, sp.csr_matrix):
            raise ValueError('Parameter[B] must be (N_px, N_px) CSR.')
        self._B = B
        if not isinstance(p, Parameter):
            raise ValueError('Parameter[p]: expected deepwave.nn.crnn.Parameter')
        self._p = p

    def eval(self, p, x):
        """Evaluate f(p, x). Parameters ---------- p : :py:class:`~numpy.ndarray` (N_cell_1,) vectorized parameter encoding, output of :py:meth:`~deepwave.nn.crnn.Parameter.encode`. x : :py:class:`~numpy.ndarray` ([N_sample,], N_cell_2) vectorized sample encoding, output of :py:meth:`~deepwave.nn.Sampler.encode`. Several samples can be provided if stacked along axis 0. This variable is not used in the implementation, but is provided for interface consistency. Returns ------- z : float z = f(p)"""
        _, _, tau = self._p.decode(p)
        N_px = tau.size
        z = 0.5 * self._lambda_ / N_px * (tau @ self._B.dot(tau))
        return z

    def grad(self, p, x):
        """Evaluate \\grad_{p} f(p, x). Parameters ---------- p : :py:class:`~numpy.ndarray` (N_cell_1,) vectorized parameter encoding, output of :py:meth:`~deepwave.nn.crnn.Parameter.encode`. x : :py:class:`~numpy.ndarray` ([N_sample,], N_cell_2) vectorized sample encoding, output of :py:meth:`~deepwave.nn.Sampler.encode`. Several samples can be provided if stacked along axis 0. This variable is not used in the implementation, but is provided for interface consistency. Returns ------- z : :py:class:`~numpy.ndarray` (N_cell_1,) vectorized parameter gradient, output of :py:meth:`~deepwave.nn.crnn.Parameter.encode`. z = \\grad_{p}{f(p)}"""
        _, _, tau = self._p.decode(p)
        N_px = tau.size
        dtau = self._lambda_ / N_px * self._B.T.dot(tau)
        z = self._p.encode(tau=dtau)
        return z


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

Class description:
Implement the RegionFunctionTests class.

Method signatures and docstrings:
- def test_set_new_service_1(self): This checks to make sure that you can set new services.
- def test_set_new_service_2(self): Checks to make sure that the service added and the rate given, to it are the same as the ones returned.
- def test_set_new_service_fail(self): Checks that the function fail if given parameters of the wrong types.
- def test_get_service_by_type_name(self): Checks that the services being added are the same as the ones being returned.
- def test_get_service_by_type_name_fail(self): Checks that the function fails if given parameters of the wrong types.

Implement the Python class `RegionFunctionTests` described below.

Class description:
Implement the RegionFunctionTests class.

Method signatures and docstrings:
- def test_set_new_service_1(self): This checks to make sure that you can set new services.
- def test_set_new_service_2(self): Checks to make sure that the service added and the rate given, to it are the same as the ones returned.
- def test_set_new_service_fail(self): Checks that the function fail if given parameters of the wrong types.
- def test_get_service_by_type_name(self): Checks that the services being added are the same as the ones being returned.
- def test_get_service_by_type_name_fail(self): Checks that the function fails if given parameters of the wrong types.

<|skeleton|>
class RegionFunctionTests:

    def test_set_new_service_1(self):
        """This checks to make sure that you can set new services."""
        <|body_0|>

    def test_set_new_service_2(self):
        """Checks to make sure that the service added and the rate given, to it are the same as the ones returned."""
        <|body_1|>

    def test_set_new_service_fail(self):
        """Checks that the function fail if given parameters of the wrong types."""
        <|body_2|>

    def test_get_service_by_type_name(self):
        """Checks that the services being added are the same as the ones being returned."""
        <|body_3|>

    def test_get_service_by_type_name_fail(self):
        """Checks that the function fails if given parameters of the wrong types."""
        <|body_4|>

<|end_skeleton|>

<|body_start_0|>
        serv1 = Service_Type.objects.create(name='things', pretty_name='Things', description='stuff')
        serv2 = Service_Type.objects.create(name='morethings', pretty_name='More Things', description='stuff')
        loc = Region.objects.create(name='place')
        loc.set_new_service(serv1, start_rate=0.5)
        loc.set_new_service(serv2, start_rate=0.5)
        self.assertEquals(loc.get_service_by_type_name('things').service_type, serv1)
<|end_body_0|>

<|body_start_1|>
        serv1 = Service_Type.objects.create(name='things', pretty_name='Things', description='stuff')
        loc = Region.objects.create(name='place')
        loc.set_new_service(serv1, start_rate=0.5)
        self.assertEquals(loc.get_service_by_type_name('things').service_type, serv1)
        rate = loc.get_service_by_type_name('things').get_current_rate()
        self.assertEquals(rate.rate, 0.5)
<|end_body_1|>

<|body_start_2|>
        loc = Region.objects.create(name='place')
        with self.assertRaises(TypeError):
            loc.set_new_service(service_type=5, start_rate=0.5)
        with self.assertRaises(TypeError):
            loc.set_new_service(name='things', description='stuff', start_rate='not a number')
        with self.assertRaises(TypeError):
            loc.set_new_service(name='things', description='stuff', start_rate=-5)
<|end_body_2|>

<|body_start_3|>
        serv1 = Service_Type.objects.create(name='things', pretty_name='Things', description='stuff')
        serv2 = Service_Type.objects.create(name='things2', pretty_name='things 2', description='stuff')
        loc = Region.objects.create(name='place')
        loc.set_new_service(serv1, start_rate=0.5)
        loc.set_new_service(serv2, start_rate=0.5)
        self.assertEquals(loc.get_service_by_type_name('things').service_type, serv1)
        self.assertEquals(loc.get_service_by_type_name('things2').service_type, serv2)
<|end_body_3|>

<|body_start_4|>
        loc = Region.objects.create(name='place')
        with self.assertRaises(TypeError):
            loc.get_service_by_type_name(name=2)
        with self.assertRaises(TypeError):
            loc.get_service_by_type_name(name='s p a c e ! ! ! !')
<|end_body_4|>

Solution:
class RegionFunctionTests:
    def test_set_new_service_1(self):
        """This checks to make sure that you can set new services."""
        serv1 = Service_Type.objects.create(name='things', pretty_name='Things', description='stuff')
        serv2 = Service_Type.objects.create(name='morethings', pretty_name='More Things', description='stuff')
        loc = Region.objects.create(name='place')
        loc.set_new_service(serv1, start_rate=0.5)
        loc.set_new_service(serv2, start_rate=0.5)
        self.assertEquals(loc.get_service_by_type_name('things').service_type, serv1)

    def test_set_new_service_2(self):
        """Checks to make sure that the service added and the rate given, to it are the same as the ones returned."""
        serv1 = Service_Type.objects.create(name='things', pretty_name='Things', description='stuff')
        loc = Region.objects.create(name='place')
        loc.set_new_service(serv1, start_rate=0.5)
        self.assertEquals(loc.get_service_by_type_name('things').service_type, serv1)
        rate = loc.get_service_by_type_name('things').get_current_rate()
        self.assertEquals(rate.rate, 0.5)

    def test_set_new_service_fail(self):
        """Checks that the function fail if given parameters of the wrong types."""
        loc = Region.objects.create(name='place')
        with self.assertRaises(TypeError):
            loc.set_new_service(service_type=5, start_rate=0.5)
        with self.assertRaises(TypeError):
            loc.set_new_service(name='things', description='stuff', start_rate='not a number')
        with self.assertRaises(TypeError):
            loc.set_new_service(name='things', description='stuff', start_rate=-5)

    def test_get_service_by_type_name(self):
        """Checks that the services being added are the same as the ones being returned."""
        serv1 = Service_Type.objects.create(name='things', pretty_name='Things', description='stuff')
        serv2 = Service_Type.objects.create(name='things2', pretty_name='things 2', description='stuff')
        loc = Region.objects.create(name='place')
        loc.set_new_service(serv1, start_rate=0.5)
        loc.set_new_service(serv2, start_rate=0.5)
        self.assertEquals(loc.get_service_by_type_name('things').service_type, serv1)
        self.assertEquals(loc.get_service_by_type_name('things2').service_type, serv2)

    def test_get_service_by_type_name_fail(self):
        """Checks that the function fails if given parameters of the wrong types."""
        loc = Region.objects.create(name='place')
        with self.assertRaises(TypeError):
            loc.get_service_by_type_name(name=2)
        with self.assertRaises(TypeError):
            loc.get_service_by_type_name(name='s p a c e ! ! ! !')


testParseEval

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

Class description:
Implement the testParsingEvaling class.

Method signatures and docstrings:
- def testParsedRepr(self): Test the ability of all matchers to be parsed and to report themselves.
- def testStableRepr(self): Test that reparsing the string version of a matcher gets the same result.
- def testParseEval(self): Test that we properly parse and evaluate known strings.

Implement the Python class `testParsingEvaling` described below.

Class description:
Implement the testParsingEvaling class.

Method signatures and docstrings:
- def testParsedRepr(self): Test the ability of all matchers to be parsed and to report themselves.
- def testStableRepr(self): Test that reparsing the string version of a matcher gets the same result.
- def testParseEval(self): Test that we properly parse and evaluate known strings.

<|skeleton|>
class testParsingEvaling:

    def testParsedRepr(self):
        """Test the ability of all matchers to be parsed and to report themselves."""
        <|body_0|>

    def testStableRepr(self):
        """Test that reparsing the string version of a matcher gets the same result."""
        <|body_1|>

    def testParseEval(self):
        """Test that we properly parse and evaluate known strings."""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        for p, res in self.basicOps:
            tree = rdparse.parse(p, matchers.matchinfo)
            self.assertEqual(str(tree), res)
<|end_body_0|>

<|body_start_1|>
        for p, res in self.basicOps:
            s1 = str(rdparse.parse(p, matchers.matchinfo))
            s2 = str(rdparse.parse(s1, matchers.matchinfo))
            self.assertEqual(s1, s2, '%s did not stabilize' % (p,))
<|end_body_1|>

<|body_start_2|>
        for testline in self.knownParseEvals:
            pstr = testline[0]
            pres = testline[1]
            root = rdparse.parse(pstr, matchers.matchinfo)
            self.assertEqual(str(root), pres)
            r2 = rdparse.parse(pres, matchers.matchinfo)
            self.assertEqual(str(r2), pres, '%s did not reparse identical' % (pres,))
            for ip, res in testline[2:]:
                hi = makehi(rip=ip)
                hi.addclass('frotz')
                self.assertEqual(root.eval(hi), res, '%s failed on host %s' % (pstr, ip))
<|end_body_2|>

Solution:
class testParsingEvaling:
    def testParsedRepr(self):
        """Test the ability of all matchers to be parsed and to report themselves."""
        for p, res in self.basicOps:
            tree = rdparse.parse(p, matchers.matchinfo)
            self.assertEqual(str(tree), res)

    def testStableRepr(self):
        """Test that reparsing the string version of a matcher gets the same result."""
        for p, res in self.basicOps:
            s1 = str(rdparse.parse(p, matchers.matchinfo))
            s2 = str(rdparse.parse(s1, matchers.matchinfo))
            self.assertEqual(s1, s2, '%s did not stabilize' % (p,))

    def testParseEval(self):
        """Test that we properly parse and evaluate known strings."""
        for testline in self.knownParseEvals:
            pstr = testline[0]
            pres = testline[1]
            root = rdparse.parse(pstr, matchers.matchinfo)
            self.assertEqual(str(root), pres)
            r2 = rdparse.parse(pres, matchers.matchinfo)
            self.assertEqual(str(r2), pres, '%s did not reparse identical' % (pres,))
            for ip, res in testline[2:]:
                hi = makehi(rip=ip)
                hi.addclass('frotz')
                self.assertEqual(root.eval(hi), res, '%s failed on host %s' % (pstr, ip))


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

Class description:
Agent Class that implements a planning agent The GetClosestPersonOrRefill class is a subclass of Agent that implements a specific agent whose objective is to collect the closest available person or refuelling, by using A* search with manhattan distance as heuristic. On each step this agent perform a new A* search until the problem reached a goal state. Also, it always process the actions in the following order: 'UP', 'RIGHT', 'DOWN', 'LEFT', 'REFILL', 'STOP' and in case of ties when computing the heuristic, it uses a FIFO tie-breaker heuristic to pop from the priority queue. .. notes:: The code below is provided to you as a guide and it is completely functional. Since you will only use it to

Method signatures and docstrings:
- def __init__(self, **kwargs): As stated before, all information that will be passed during the initialization is packed in the kwargs and, because of that, unless you decided to implement fancy attributes here, you can safely pass the kwargs dictionary directly to the superclass constructor. For pedagogical reasons, we decided that we will instatiate additional attributes here that will be later set via start_agent method.
- def __state_from_perception(self, perception): Private method to help to convert a perception into a state This is a helper method that converts a perception passed from the environment into a state to be used in the search problem. :param perception: The perception your agent acquires from the environment. :type perception: Problem dependent (for this programming assignment a tuple with the grid matrix and the remaining fuel for your agent) :return: A problem state according with your conception of problem. (E.g. for GetClosestPersonOrRefillProblem, we chose a state as a tuple with the agent coordinates and its remaining fuel)
- def start_agent(self, perception, problem, **kwargs): Initialize all non-default attributes in the agent This is a helper method to allow the instantiation of all non-default attributes from this class. In this particular case, we are instantiating a search problem according with the perception and the specs provided.
- def manhattan_distance(self, node): Heuristic to be used by the A* algorithm
- def get_action(self, perception): This is the main method for all your agents Along with the __init__, you must at least implement this method in all your agents to make them work properly. This method receives a perception from the environment and returns an action after performing the A* search with manhattan_distance as heuristics.

Implement the Python class `GetClosestPersonOrRefillAgent` described below.

Class description:
Agent Class that implements a planning agent The GetClosestPersonOrRefill class is a subclass of Agent that implements a specific agent whose objective is to collect the closest available person or refuelling, by using A* search with manhattan distance as heuristic. On each step this agent perform a new A* search until the problem reached a goal state. Also, it always process the actions in the following order: 'UP', 'RIGHT', 'DOWN', 'LEFT', 'REFILL', 'STOP' and in case of ties when computing the heuristic, it uses a FIFO tie-breaker heuristic to pop from the priority queue. .. notes:: The code below is provided to you as a guide and it is completely functional. Since you will only use it to

Method signatures and docstrings:
- def __init__(self, **kwargs): As stated before, all information that will be passed during the initialization is packed in the kwargs and, because of that, unless you decided to implement fancy attributes here, you can safely pass the kwargs dictionary directly to the superclass constructor. For pedagogical reasons, we decided that we will instatiate additional attributes here that will be later set via start_agent method.
- def __state_from_perception(self, perception): Private method to help to convert a perception into a state This is a helper method that converts a perception passed from the environment into a state to be used in the search problem. :param perception: The perception your agent acquires from the environment. :type perception: Problem dependent (for this programming assignment a tuple with the grid matrix and the remaining fuel for your agent) :return: A problem state according with your conception of problem. (E.g. for GetClosestPersonOrRefillProblem, we chose a state as a tuple with the agent coordinates and its remaining fuel)
- def start_agent(self, perception, problem, **kwargs): Initialize all non-default attributes in the agent This is a helper method to allow the instantiation of all non-default attributes from this class. In this particular case, we are instantiating a search problem according with the perception and the specs provided.
- def manhattan_distance(self, node): Heuristic to be used by the A* algorithm
- def get_action(self, perception): This is the main method for all your agents Along with the __init__, you must at least implement this method in all your agents to make them work properly. This method receives a perception from the environment and returns an action after performing the A* search with manhattan_distance as heuristics.

<|skeleton|>
class GetClosestPersonOrRefillAgent:
    """Agent Class that implements a planning agent The GetClosestPersonOrRefill class is a subclass of Agent that implements a specific agent whose objective is to collect the closest available person or refuelling, by using A* search with manhattan distance as heuristic. On each step this agent perform a new A* search until the problem reached a goal state. Also, it always process the actions in the following order: 'UP', 'RIGHT', 'DOWN', 'LEFT', 'REFILL', 'STOP' and in case of ties when computing the heuristic, it uses a FIFO tie-breaker heuristic to pop from the priority queue. .. notes:: The code below is provided to you as a guide and it is completely functional. Since you will only use it to"""

    def __init__(self, **kwargs):
        """As stated before, all information that will be passed during the initialization is packed in the kwargs and, because of that, unless you decided to implement fancy attributes here, you can safely pass the kwargs dictionary directly to the superclass constructor. For pedagogical reasons, we decided that we will instatiate additional attributes here that will be later set via start_agent method."""
        <|body_0|>

    def __state_from_perception(self, perception):
        """Private method to help to convert a perception into a state This is a helper method that converts a perception passed from the environment into a state to be used in the search problem. :param perception: The perception your agent acquires from the environment. :type perception: Problem dependent (for this programming assignment a tuple with the grid matrix and the remaining fuel for your agent) :return: A problem state according with your conception of problem. (E.g. for GetClosestPersonOrRefillProblem, we chose a state as a tuple with the agent coordinates and its remaining fuel)"""
        <|body_1|>

    def start_agent(self, perception, problem, **kwargs):
        """Initialize all non-default attributes in the agent This is a helper method to allow the instantiation of all non-default attributes from this class. In this particular case, we are instantiating a search problem according with the perception and the specs provided."""
        <|body_2|>

    def manhattan_distance(self, node):
        """Heuristic to be used by the A* algorithm"""
        <|body_3|>

    def get_action(self, perception):
        """This is the main method for all your agents Along with the __init__, you must at least implement this method in all your agents to make them work properly. This method receives a perception from the environment and returns an action after performing the A* search with manhattan_distance as heuristics."""
        <|body_4|>

<|end_skeleton|>

<|body_start_0|>
        super().__init__(**kwargs)
        self.problem_reference = GetClosestPersonOrRefillProblem
        self.problem = None
<|end_body_0|>

<|body_start_1|>
        grid, remaining_gas = perception
        player_values = [self.player_number, self.player_number + 7]
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j] in player_values:
                    return ((i, j), remaining_gas)
        return None
<|end_body_1|>

<|body_start_2|>
        self.initial_state = self.__state_from_perception(perception)
        grid, _ = perception
        new_grid = copy.deepcopy(grid)
        self.problem = problem(new_grid, self.initial_state, **kwargs)
<|end_body_2|>

<|body_start_3|>
        goals = self.problem.get_people_position()
        state = node.state[0]
        best_distance = util.INT_INFTY
        for people in goals:
            manhattan = abs(state[0] - people[0]) + abs(state[1] - people[1])
            if manhattan < best_distance:
                best_distance = manhattan
        return best_distance
<|end_body_3|>

<|body_start_4|>
        self.start_agent(perception, self.problem_reference, tank_capacity=self.tank_capacity)
        node = util.a_star(self.problem, self.manhattan_distance)
        if not node:
            return 'STOP'
        action = node.action
        last_action = None
        while node.parent is not None:
            node = node.parent
            last_action = action
            action = node.action
        return last_action
<|end_body_4|>

Solution:
class GetClosestPersonOrRefillAgent:
    """Agent Class that implements a planning agent The GetClosestPersonOrRefill class is a subclass of Agent that implements a specific agent whose objective is to collect the closest available person or refuelling, by using A* search with manhattan distance as heuristic. On each step this agent perform a new A* search until the problem reached a goal state. Also, it always process the actions in the following order: 'UP', 'RIGHT', 'DOWN', 'LEFT', 'REFILL', 'STOP' and in case of ties when computing the heuristic, it uses a FIFO tie-breaker heuristic to pop from the priority queue. .. notes:: The code below is provided to you as a guide and it is completely functional. Since you will only use it to"""

    def __init__(self, **kwargs):
        """As stated before, all information that will be passed during the initialization is packed in the kwargs and, because of that, unless you decided to implement fancy attributes here, you can safely pass the kwargs dictionary directly to the superclass constructor. For pedagogical reasons, we decided that we will instatiate additional attributes here that will be later set via start_agent method."""
        super().__init__(**kwargs)
        self.problem_reference = GetClosestPersonOrRefillProblem
        self.problem = None

    def __state_from_perception(self, perception):
        """Private method to help to convert a perception into a state This is a helper method that converts a perception passed from the environment into a state to be used in the search problem. :param perception: The perception your agent acquires from the environment. :type perception: Problem dependent (for this programming assignment a tuple with the grid matrix and the remaining fuel for your agent) :return: A problem state according with your conception of problem. (E.g. for GetClosestPersonOrRefillProblem, we chose a state as a tuple with the agent coordinates and its remaining fuel)"""
        grid, remaining_gas = perception
        player_values = [self.player_number, self.player_number + 7]
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j] in player_values:
                    return ((i, j), remaining_gas)
        return None

    def start_agent(self, perception, problem, **kwargs):
        """Initialize all non-default attributes in the agent This is a helper method to allow the instantiation of all non-default attributes from this class. In this particular case, we are instantiating a search problem according with the perception and the specs provided."""
        self.initial_state = self.__state_from_perception(perception)
        grid, _ = perception
        new_grid = copy.deepcopy(grid)
        self.problem = problem(new_grid, self.initial_state, **kwargs)

    def manhattan_distance(self, node):
        """Heuristic to be used by the A* algorithm"""
        goals = self.problem.get_people_position()
        state = node.state[0]
        best_distance = util.INT_INFTY
        for people in goals:
            manhattan = abs(state[0] - people[0]) + abs(state[1] - people[1])
            if manhattan < best_distance:
                best_distance = manhattan
        return best_distance

    def get_action(self, perception):
        """This is the main method for all your agents Along with the __init__, you must at least implement this method in all your agents to make them work properly. This method receives a perception from the environment and returns an action after performing the A* search with manhattan_distance as heuristics."""
        self.start_agent(perception, self.problem_reference, tank_capacity=self.tank_capacity)
        node = util.a_star(self.problem, self.manhattan_distance)
        if not node:
            return 'STOP'
        action = node.action
        last_action = None
        while node.parent is not None:
            node = node.parent
            last_action = action
            action = node.action
        return last_action


paste

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

Class description:
Create highlighted code-boxes with one command.

Method signatures and docstrings:
- async def hl(self, ctx, *, code): Highlight some code.
- async def on_raw_reaction_add(self, payload): Listens for raw reactions and removes a highlighted message if appropriate.
- async def lang(self, ctx, *, language: lang_converter=None): Set your preferred highlighting language in this server.
- async def serverlang(self, ctx, *, language: lang_converter): Set a guild-specific highlighting language. Can be overridden individually by users.
- async def paste(self, ctx): Legacy, not removed because some people still use it instead of the newer tags in the tag system.

Implement the Python class `Highlighter` described below.

Class description:
Create highlighted code-boxes with one command.

Method signatures and docstrings:
- async def hl(self, ctx, *, code): Highlight some code.
- async def on_raw_reaction_add(self, payload): Listens for raw reactions and removes a highlighted message if appropriate.
- async def lang(self, ctx, *, language: lang_converter=None): Set your preferred highlighting language in this server.
- async def serverlang(self, ctx, *, language: lang_converter): Set a guild-specific highlighting language. Can be overridden individually by users.
- async def paste(self, ctx): Legacy, not removed because some people still use it instead of the newer tags in the tag system.

<|skeleton|>
class Highlighter:
    """Create highlighted code-boxes with one command."""

    async def hl(self, ctx, *, code):
        """Highlight some code."""
        <|body_0|>

    async def on_raw_reaction_add(self, payload):
        """Listens for raw reactions and removes a highlighted message if appropriate."""
        <|body_1|>

    async def lang(self, ctx, *, language: lang_converter=None):
        """Set your preferred highlighting language in this server."""
        <|body_2|>

    async def serverlang(self, ctx, *, language: lang_converter):
        """Set a guild-specific highlighting language. Can be overridden individually by users."""
        <|body_3|>

    async def paste(self, ctx):
        """Legacy, not removed because some people still use it instead of the newer tags in the tag system."""
        <|body_4|>

<|end_skeleton|>

<|body_start_0|>
        await ctx.message.delete()
        code = ctx.message.content[len(ctx.prefix) + 3:]
        code = code.replace('``', '`\u200b`')
        code = re.sub('\n\n+', '\n\n', code)
        code = code.strip()
        lang = await self.db.fetchval('SELECT lang FROM highlight_lang WHERE guild_id=$1 AND (user_id=$2 OR user_id=$3)', ctx.guild.id, 0, ctx.author.id) or DEFAULT_LANG
        code = '```{}\n{}\n```'.format(lang, code)
        code += '*Paste by {0} - Click {1} to delete.*'.format(ctx.author.mention, DELETE_EMOJI)
        if len(code) > 2000:
            raise commands.CommandError('Code contents too long to paste.')
        message = await ctx.send(code)
        await self.db.execute('INSERT INTO highlight_msg (guild_id, channel_id, user_id, message_id) VALUES ($1, $2, $3, $4)', ctx.guild.id, ctx.channel.id, ctx.author.id, message.id)
        await message.add_reaction(DELETE_EMOJI)
<|end_body_0|>

<|body_start_1|>
        if payload.guild_id is None:
            return
        if str(payload.emoji) != DELETE_EMOJI or payload.user_id == self.bot.user.id:
            return
        if await self.db.execute('DELETE FROM highlight_msg WHERE user_id=$1 AND message_id=$2', payload.user_id, payload.message_id) == 'DELETE 0':
            return
        channel = self.bot.get_channel(payload.channel_id)
        if channel is None:
            return
        try:
            message = await channel.fetch_message(payload.message_id)
            await message.delete()
        except disnake.HTTPException:
            return
<|end_body_1|>

<|body_start_2|>
        if language is None:
            server_lang = await self.db.fetchval('SELECT lang FROM highlight_lang WHERE guild_id=$1 AND user_id=$2', ctx.guild.id, 0)
            user_lang = await self.db.fetchval('SELECT lang FROM highlight_lang WHERE guild_id=$1 AND user_id=$2', ctx.guild.id, ctx.author.id)
            e = disnake.Embed(description='Do `.lang clear` to clear preference.')
            e.add_field(name='Server setting', value=f"`{(DEFAULT_LANG + ' (default)' if server_lang is None else server_lang)}`")
            e.add_field(name='Personal setting', value='Not set' if user_lang is None else f'`{user_lang}`')
            await ctx.send(embed=e)
            return
        if language == 'clear':
            ret = await self.db.execute('DELETE FROM highlight_lang WHERE guild_id=$1 AND user_id=$2', ctx.guild.id, ctx.author.id)
            await ctx.send('No preference previously set' if ret == 'DELETE 0' else 'Preference cleared.')
        else:
            await self.db.execute('INSERT INTO highlight_lang (guild_id, user_id, lang) VALUES ($1, $2, $3) ON CONFLICT (guild_id, user_id) DO UPDATE SET lang=$3', ctx.guild.id, ctx.author.id, language)
            await ctx.send(f"Set your specific highlighting language to '{language}'.")
<|end_body_2|>

<|body_start_3|>
        if language == 'clear':
            ret = await self.db.execute('DELETE FROM highlight_lang WHERE guild_id=$1 AND user_id=$2', ctx.guild.id, 0)
            await ctx.send('No preference previously set' if ret == 'DELETE 0' else 'Preference cleared.')
        else:
            await self.db.execute('INSERT INTO highlight_lang (guild_id, user_id, lang) VALUES ($1, $2, $3) ON CONFLICT (guild_id, user_id) DO UPDATE SET lang=$3', ctx.guild.id, 0, language)
            await ctx.send(f"Set server-specific highlighting language to '{language}'.")
<|end_body_3|>

<|body_start_4|>
        msg = 'To paste code snippets directly into the chat, use the highlight command:\n```.hl *paste code here*```'
        if ctx.guild.id == AHK_GUILD_ID:
            msg += 'If you have a larger script you want to share, paste it to the AutoHotkey pastebin instead:\nhttp://p.ahkscript.org/'
        await ctx.send(msg)
<|end_body_4|>

Solution:
class Highlighter:
    """Create highlighted code-boxes with one command."""

    async def hl(self, ctx, *, code):
        """Highlight some code."""
        await ctx.message.delete()
        code = ctx.message.content[len(ctx.prefix) + 3:]
        code = code.replace('``', '`\u200b`')
        code = re.sub('\n\n+', '\n\n', code)
        code = code.strip()
        lang = await self.db.fetchval('SELECT lang FROM highlight_lang WHERE guild_id=$1 AND (user_id=$2 OR user_id=$3)', ctx.guild.id, 0, ctx.author.id) or DEFAULT_LANG
        code = '```{}\n{}\n```'.format(lang, code)
        code += '*Paste by {0} - Click {1} to delete.*'.format(ctx.author.mention, DELETE_EMOJI)
        if len(code) > 2000:
            raise commands.CommandError('Code contents too long to paste.')
        message = await ctx.send(code)
        await self.db.execute('INSERT INTO highlight_msg (guild_id, channel_id, user_id, message_id) VALUES ($1, $2, $3, $4)', ctx.guild.id, ctx.channel.id, ctx.author.id, message.id)
        await message.add_reaction(DELETE_EMOJI)

    async def on_raw_reaction_add(self, payload):
        """Listens for raw reactions and removes a highlighted message if appropriate."""
        if payload.guild_id is None:
            return
        if str(payload.emoji) != DELETE_EMOJI or payload.user_id == self.bot.user.id:
            return
        if await self.db.execute('DELETE FROM highlight_msg WHERE user_id=$1 AND message_id=$2', payload.user_id, payload.message_id) == 'DELETE 0':
            return
        channel = self.bot.get_channel(payload.channel_id)
        if channel is None:
            return
        try:
            message = await channel.fetch_message(payload.message_id)
            await message.delete()
        except disnake.HTTPException:
            return

    async def lang(self, ctx, *, language: lang_converter=None):
        """Set your preferred highlighting language in this server."""
        if language is None:
            server_lang = await self.db.fetchval('SELECT lang FROM highlight_lang WHERE guild_id=$1 AND user_id=$2', ctx.guild.id, 0)
            user_lang = await self.db.fetchval('SELECT lang FROM highlight_lang WHERE guild_id=$1 AND user_id=$2', ctx.guild.id, ctx.author.id)
            e = disnake.Embed(description='Do `.lang clear` to clear preference.')
            e.add_field(name='Server setting', value=f"`{(DEFAULT_LANG + ' (default)' if server_lang is None else server_lang)}`")
            e.add_field(name='Personal setting', value='Not set' if user_lang is None else f'`{user_lang}`')
            await ctx.send(embed=e)
            return
        if language == 'clear':
            ret = await self.db.execute('DELETE FROM highlight_lang WHERE guild_id=$1 AND user_id=$2', ctx.guild.id, ctx.author.id)
            await ctx.send('No preference previously set' if ret == 'DELETE 0' else 'Preference cleared.')
        else:
            await self.db.execute('INSERT INTO highlight_lang (guild_id, user_id, lang) VALUES ($1, $2, $3) ON CONFLICT (guild_id, user_id) DO UPDATE SET lang=$3', ctx.guild.id, ctx.author.id, language)
            await ctx.send(f"Set your specific highlighting language to '{language}'.")

    async def serverlang(self, ctx, *, language: lang_converter):
        """Set a guild-specific highlighting language. Can be overridden individually by users."""
        if language == 'clear':
            ret = await self.db.execute('DELETE FROM highlight_lang WHERE guild_id=$1 AND user_id=$2', ctx.guild.id, 0)
            await ctx.send('No preference previously set' if ret == 'DELETE 0' else 'Preference cleared.')
        else:
            await self.db.execute('INSERT INTO highlight_lang (guild_id, user_id, lang) VALUES ($1, $2, $3) ON CONFLICT (guild_id, user_id) DO UPDATE SET lang=$3', ctx.guild.id, 0, language)
            await ctx.send(f"Set server-specific highlighting language to '{language}'.")

    async def paste(self, ctx):
        """Legacy, not removed because some people still use it instead of the newer tags in the tag system."""
        msg = 'To paste code snippets directly into the chat, use the highlight command:\n```.hl *paste code here*```'
        if ctx.guild.id == AHK_GUILD_ID:
            msg += 'If you have a larger script you want to share, paste it to the AutoHotkey pastebin instead:\nhttp://p.ahkscript.org/'
        await ctx.send(msg)


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

Class description:
Type d'objet: sextant.

Method signatures and docstrings:
- def __init__(self, cle=''): Constructeur de l'objet
- def travailler_enveloppes(self, enveloppes): Travail sur les enveloppes
- def regarder(self, personnage): Quand on regarde la sextant.

Implement the Python class `Sextant` described below.

Class description:
Type d'objet: sextant.

Method signatures and docstrings:
- def __init__(self, cle=''): Constructeur de l'objet
- def travailler_enveloppes(self, enveloppes): Travail sur les enveloppes
- def regarder(self, personnage): Quand on regarde la sextant.

<|skeleton|>
class Sextant:
    """Type d'objet: sextant."""

    def __init__(self, cle=''):
        """Constructeur de l'objet"""
        <|body_0|>

    def travailler_enveloppes(self, enveloppes):
        """Travail sur les enveloppes"""
        <|body_1|>

    def regarder(self, personnage):
        """Quand on regarde la sextant."""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        Instrument.__init__(self, cle)
        self.emplacement = 'mains'
        self.positions = (1, 2)
        self.precision = 10
        self.calcul = 60
        self.etendre_editeur('r', 'précision', Uniligne, self, 'precision')
        self.etendre_editeur('ca', 'temps de calcul', Uniligne, self, 'calcul')
<|end_body_0|>

<|body_start_1|>
        precision = enveloppes['r']
        precision.apercu = '{objet.precision}'
        precision.prompt = 'Précision (en minutes) du sextant : '
        precision.aide_courte = 'Entrez la |ent|précision|ff| du sextant, |cmd|1|ff| au minimum.\nPlus le chiffre est bas, plus le sextant est précis.\nNotez que le sextant est toujours précis en degrés, la précision\nest en minutes.\nEntrez |cmd|/|ff| pour revenir à la fenêtre parente.\n\nPrécision actuelle : {objet.precision}'
        precision.type = int
        calcul = enveloppes['ca']
        calcul.apercu = '{objet.calcul} secondes'
        calcul.prompt = 'Temps de calcul nécessaire (en secondes) : '
        calcul.aide_courte = 'Entrez le |ent|temps de calcul|ff| du sextant en secondes.\nEntrez |cmd|/|ff| pour revenir à la fenêtre parente.\n\nTemps actuelle : {objet.calcul} secondes'
        calcul.type = int
<|end_body_1|>

<|body_start_2|>
        moi = Instrument.regarder(self, personnage)
        personnage.envoyer_tip('Entrez la commande %point% pour faire le point.')
        return moi
<|end_body_2|>

Solution:
class Sextant:
    """Type d'objet: sextant."""

    def __init__(self, cle=''):
        """Constructeur de l'objet"""
        Instrument.__init__(self, cle)
        self.emplacement = 'mains'
        self.positions = (1, 2)
        self.precision = 10
        self.calcul = 60
        self.etendre_editeur('r', 'précision', Uniligne, self, 'precision')
        self.etendre_editeur('ca', 'temps de calcul', Uniligne, self, 'calcul')

    def travailler_enveloppes(self, enveloppes):
        """Travail sur les enveloppes"""
        precision = enveloppes['r']
        precision.apercu = '{objet.precision}'
        precision.prompt = 'Précision (en minutes) du sextant : '
        precision.aide_courte = 'Entrez la |ent|précision|ff| du sextant, |cmd|1|ff| au minimum.\nPlus le chiffre est bas, plus le sextant est précis.\nNotez que le sextant est toujours précis en degrés, la précision\nest en minutes.\nEntrez |cmd|/|ff| pour revenir à la fenêtre parente.\n\nPrécision actuelle : {objet.precision}'
        precision.type = int
        calcul = enveloppes['ca']
        calcul.apercu = '{objet.calcul} secondes'
        calcul.prompt = 'Temps de calcul nécessaire (en secondes) : '
        calcul.aide_courte = 'Entrez le |ent|temps de calcul|ff| du sextant en secondes.\nEntrez |cmd|/|ff| pour revenir à la fenêtre parente.\n\nTemps actuelle : {objet.calcul} secondes'
        calcul.type = int

    def regarder(self, personnage):
        """Quand on regarde la sextant."""
        moi = Instrument.regarder(self, personnage)
        personnage.envoyer_tip('Entrez la commande %point% pour faire le point.')
        return moi


Available

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

Class description:
User task that starts flow from a django view.

Method signatures and docstrings:
- def Available(self, owner=None, **owner_kwargs): Make process start action available for the User. Accepts user lookup kwargs or callable predicate :: User -> bool:: .Available(username='employee') .Available(lambda user: user.is_super_user)
- def get_task_url(self, task, url_type='guess', namespace='', **kwargs): "Handle url_Type='execute'. If url_type is 'guess' and task can be executed by user, the 'execute' url is returned.
- def can_execute(self, user, task=None): Check user permission to start a flow.

Implement the Python class `Start` described below.

Class description:
User task that starts flow from a django view.

Method signatures and docstrings:
- def Available(self, owner=None, **owner_kwargs): Make process start action available for the User. Accepts user lookup kwargs or callable predicate :: User -> bool:: .Available(username='employee') .Available(lambda user: user.is_super_user)
- def get_task_url(self, task, url_type='guess', namespace='', **kwargs): "Handle url_Type='execute'. If url_type is 'guess' and task can be executed by user, the 'execute' url is returned.
- def can_execute(self, user, task=None): Check user permission to start a flow.

<|skeleton|>
class Start:
    """User task that starts flow from a django view."""

    def Available(self, owner=None, **owner_kwargs):
        """Make process start action available for the User. Accepts user lookup kwargs or callable predicate :: User -> bool:: .Available(username='employee') .Available(lambda user: user.is_super_user)"""
        <|body_0|>

    def get_task_url(self, task, url_type='guess', namespace='', **kwargs):
        """"Handle url_Type='execute'. If url_type is 'guess' and task can be executed by user, the 'execute' url is returned."""
        <|body_1|>

    def can_execute(self, user, task=None):
        """Check user permission to start a flow."""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        if owner:
            self._owner = owner
        else:
            self._owner = owner_kwargs
        return self
<|end_body_0|>

<|body_start_1|>
        if url_type in ['execute', 'guess']:
            if 'user' in kwargs and self.can_execute(kwargs['user'], task):
                url_name = '{}:{}'.format(namespace, self.name)
                return reverse(url_name)
        return super(Start, self).get_task_url(task, url_type=url_type, namespace=namespace, **kwargs)
<|end_body_1|>

<|body_start_2|>
        if task and task.status != STATUS.NEW:
            return False
        from django.contrib.auth import get_user_model
        if self._owner:
            if callable(self._owner):
                return self._owner(user)
            else:
                owner = get_user_model()._default_manager.get(**self._owner)
                return owner == user
        elif self._owner_permission:
            obj = None
            if self._owner_permission_obj:
                if callable(self._owner_permission_obj):
                    obj = self._owner_permission_obj()
                else:
                    obj = self._owner_permission_obj
            return user.has_perm(self._owner_permission, obj=obj)
        else:
            '\n            No restriction\n            '
            return True
<|end_body_2|>

Solution:
class Start:
    """User task that starts flow from a django view."""

    def Available(self, owner=None, **owner_kwargs):
        """Make process start action available for the User. Accepts user lookup kwargs or callable predicate :: User -> bool:: .Available(username='employee') .Available(lambda user: user.is_super_user)"""
        if owner:
            self._owner = owner
        else:
            self._owner = owner_kwargs
        return self

    def get_task_url(self, task, url_type='guess', namespace='', **kwargs):
        """"Handle url_Type='execute'. If url_type is 'guess' and task can be executed by user, the 'execute' url is returned."""
        if url_type in ['execute', 'guess']:
            if 'user' in kwargs and self.can_execute(kwargs['user'], task):
                url_name = '{}:{}'.format(namespace, self.name)
                return reverse(url_name)
        return super(Start, self).get_task_url(task, url_type=url_type, namespace=namespace, **kwargs)

    def can_execute(self, user, task=None):
        """Check user permission to start a flow."""
        if task and task.status != STATUS.NEW:
            return False
        from django.contrib.auth import get_user_model
        if self._owner:
            if callable(self._owner):
                return self._owner(user)
            else:
                owner = get_user_model()._default_manager.get(**self._owner)
                return owner == user
        elif self._owner_permission:
            obj = None
            if self._owner_permission_obj:
                if callable(self._owner_permission_obj):
                    obj = self._owner_permission_obj()
                else:
                    obj = self._owner_permission_obj
            return user.has_perm(self._owner_permission, obj=obj)
        else:
            '\n            No restriction\n            '
            return True


parse

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

Class description:
searches our developer domains for emails

Method signatures and docstrings:
- def __init__(self, *args, **kwargs): conencts to db
- def parse(self, response): finds emails in a rudimentary but effective way using regular expressions

Implement the Python class `EmailSpider` described below.

Class description:
searches our developer domains for emails

Method signatures and docstrings:
- def __init__(self, *args, **kwargs): conencts to db
- def parse(self, response): finds emails in a rudimentary but effective way using regular expressions

<|skeleton|>
class EmailSpider:
    """searches our developer domains for emails"""

    def __init__(self, *args, **kwargs):
        """conencts to db"""
        <|body_0|>

    def parse(self, response):
        """finds emails in a rudimentary but effective way using regular expressions"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        super().__init__(*args, **kwargs)
        db = model.SqlSession()
        urls, domains = get_start_urls(db)
        random.shuffle(urls)
        self.start_urls = urls
        self.extractor = LinkExtractor(allow_domains=domains, deny_domains=DENY_DOMAINS)
        db.close()
<|end_body_0|>

<|body_start_1|>
        for link in self.extractor.extract_links(response):
            yield scrapy.Request(url=link.url)
        yield from items.load_emails(response)
<|end_body_1|>

Solution:
class EmailSpider:
    """searches our developer domains for emails"""

    def __init__(self, *args, **kwargs):
        """conencts to db"""
        super().__init__(*args, **kwargs)
        db = model.SqlSession()
        urls, domains = get_start_urls(db)
        random.shuffle(urls)
        self.start_urls = urls
        self.extractor = LinkExtractor(allow_domains=domains, deny_domains=DENY_DOMAINS)
        db.close()

    def parse(self, response):
        """finds emails in a rudimentary but effective way using regular expressions"""
        for link in self.extractor.extract_links(response):
            yield scrapy.Request(url=link.url)
        yield from items.load_emails(response)


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

Class description:
Implement the TestGeneratorLink class.

Method signatures and docstrings:
- def test_prime(self): Prime generator for use
- def test_close(self): Release underlying generator
- def test_linklet(self): Chainlink via decorator
- def test_prime_linklet(self): Prime genlet for use

Implement the Python class `TestGeneratorLink` described below.

Class description:
Implement the TestGeneratorLink class.

Method signatures and docstrings:
- def test_prime(self): Prime generator for use
- def test_close(self): Release underlying generator
- def test_linklet(self): Chainlink via decorator
- def test_prime_linklet(self): Prime genlet for use

<|skeleton|>
class TestGeneratorLink:

    def test_prime(self):
        """Prime generator for use"""
        <|body_0|>

    def test_close(self):
        """Release underlying generator"""
        <|body_1|>

    def test_linklet(self):
        """Chainlink via decorator"""
        <|body_2|>

    def test_prime_linklet(self):
        """Prime genlet for use"""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        def generator():
            primer = (yield)
            yield primer
        prime_true = chainlet.genlink.GeneratorLink(generator(), prime=True)
        self.assertEqual(prime_true.send('pingpong'), 'pingpong')
        prime_false = chainlet.genlink.GeneratorLink(generator(), prime=False)
        self.assertIsNone(next(prime_false))
        self.assertEqual(prime_false.send('pingpong'), 'pingpong')
        for name, link in (('prime_true', prime_true), ('prime_false', prime_false)):
            with self.subTest(name=name):
                with self.assertRaises(StopIteration):
                    next(link)
<|end_body_0|>

<|body_start_1|>
        @chainlet.genlet
        def pingpong():
            last = (yield)
            while True:
                last = (yield last)
        with self.subTest(case='close'):
            genlet = pingpong()
            genlet.close()
            with self.assertRaises(StopIteration):
                next(genlet)
            with self.assertRaises(StopIteration):
                next(genlet.slave)
        with self.subTest(case='throw'):
            genlet = pingpong()
            with self.assertRaises(GeneratorExit):
                genlet.throw(GeneratorExit)
            with self.assertRaises(StopIteration):
                next(genlet)
            with self.assertRaises(StopIteration):
                next(genlet.slave)
<|end_body_1|>

<|body_start_2|>
        @chainlet.genlet
        def pingpong():
            last = (yield)
            while True:
                last = (yield last)
        test_values = [0, 22, -22, 1000000.0, 'foobar'] + [random.random() for _ in range(20)]
        with self.subTest(case='generator interface'):
            genlet = pingpong()
            for value in test_values:
                self.assertEqual(genlet.send(value), value)
                self.assertIsNone(next(genlet))
                self.assertEqual(genlet.send(value), value)
                self.assertEqual(genlet.send(value), genlet.slave.send(value))
        with self.subTest(case='chain element'):
            chain = NamedChainlet('start') >> pingpong() >> NamedChainlet('stop')
            for value in test_values:
                self.assertEqual(chain.send(value), value)
                self.assertIsNone(next(chain))
                self.assertEqual(chain.send(value), value)
        with self.subTest(case='fill chain'):
            chain = NamedChainlet('start') >> pingpong() >> pingpong() >> pingpong() >> pingpong() >> NamedChainlet('stop')
            for value in test_values:
                self.assertEqual(chain.send(value), value)
                self.assertIsNone(next(chain))
                self.assertEqual(chain.send(value), value)
<|end_body_2|>

<|body_start_3|>
        for prime in (True, False):
            with self.subTest(prime=prime):

                @chainlet.genlet(prime)
                def prime_arg():
                    primer = (yield)
                    yield primer

                @chainlet.genlet(prime=prime)
                def prime_kwarg():
                    primer = (yield)
                    yield primer
                for genlet in (prime_arg, prime_kwarg):
                    link = genlet()
                    if not prime:
                        self.assertIsNone(next(link))
                    self.assertEqual(link.send('pingpong'), 'pingpong')
                    with self.assertRaises(StopIteration):
                        next(link)
<|end_body_3|>

Solution:
class TestGeneratorLink:
    def test_prime(self):
        """Prime generator for use"""
        def generator():
            primer = (yield)
            yield primer
        prime_true = chainlet.genlink.GeneratorLink(generator(), prime=True)
        self.assertEqual(prime_true.send('pingpong'), 'pingpong')
        prime_false = chainlet.genlink.GeneratorLink(generator(), prime=False)
        self.assertIsNone(next(prime_false))
        self.assertEqual(prime_false.send('pingpong'), 'pingpong')
        for name, link in (('prime_true', prime_true), ('prime_false', prime_false)):
            with self.subTest(name=name):
                with self.assertRaises(StopIteration):
                    next(link)

    def test_close(self):
        """Release underlying generator"""
        @chainlet.genlet
        def pingpong():
            last = (yield)
            while True:
                last = (yield last)
        with self.subTest(case='close'):
            genlet = pingpong()
            genlet.close()
            with self.assertRaises(StopIteration):
                next(genlet)
            with self.assertRaises(StopIteration):
                next(genlet.slave)
        with self.subTest(case='throw'):
            genlet = pingpong()
            with self.assertRaises(GeneratorExit):
                genlet.throw(GeneratorExit)
            with self.assertRaises(StopIteration):
                next(genlet)
            with self.assertRaises(StopIteration):
                next(genlet.slave)

    def test_linklet(self):
        """Chainlink via decorator"""
        @chainlet.genlet
        def pingpong():
            last = (yield)
            while True:
                last = (yield last)
        test_values = [0, 22, -22, 1000000.0, 'foobar'] + [random.random() for _ in range(20)]
        with self.subTest(case='generator interface'):
            genlet = pingpong()
            for value in test_values:
                self.assertEqual(genlet.send(value), value)
                self.assertIsNone(next(genlet))
                self.assertEqual(genlet.send(value), value)
                self.assertEqual(genlet.send(value), genlet.slave.send(value))
        with self.subTest(case='chain element'):
            chain = NamedChainlet('start') >> pingpong() >> NamedChainlet('stop')
            for value in test_values:
                self.assertEqual(chain.send(value), value)
                self.assertIsNone(next(chain))
                self.assertEqual(chain.send(value), value)
        with self.subTest(case='fill chain'):
            chain = NamedChainlet('start') >> pingpong() >> pingpong() >> pingpong() >> pingpong() >> NamedChainlet('stop')
            for value in test_values:
                self.assertEqual(chain.send(value), value)
                self.assertIsNone(next(chain))
                self.assertEqual(chain.send(value), value)

    def test_prime_linklet(self):
        """Prime genlet for use"""
        for prime in (True, False):
            with self.subTest(prime=prime):

                @chainlet.genlet(prime)
                def prime_arg():
                    primer = (yield)
                    yield primer

                @chainlet.genlet(prime=prime)
                def prime_kwarg():
                    primer = (yield)
                    yield primer
                for genlet in (prime_arg, prime_kwarg):
                    link = genlet()
                    if not prime:
                        self.assertIsNone(next(link))
                    self.assertEqual(link.send('pingpong'), 'pingpong')
                    with self.assertRaises(StopIteration):
                        next(link)


forward

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

Class description:
Conditional Random Field. Conditional Random Field Implementation according to sgrvinod (https://github.com/sgrvinod). Classifier which predicts single tag / class / label for given word based on not just the word, but also on previous seen annotations.

Method signatures and docstrings:
- def __init__(self, tag_dictionary, tagset_size: int, init_from_state_dict: bool) -> None: Initialize the Conditional Random Field. :param tag_dictionary: tag dictionary in order to find ID for start and stop tags :param tagset_size: number of tag from tag dictionary :param init_from_state_dict: whether we load pretrained model from state dict
- def forward(self, features: torch.Tensor) -> torch.Tensor: Forward propagation of Conditional Random Field. :param features: output from RNN / Linear layer in shape (batch size, seq len, hidden size) :return: CRF scores (emission scores for each token + transitions prob from previous state) in shape (batch_size, seq len, tagset size, tagset size)

Implement the Python class `CRF` described below.

Class description:
Conditional Random Field. Conditional Random Field Implementation according to sgrvinod (https://github.com/sgrvinod). Classifier which predicts single tag / class / label for given word based on not just the word, but also on previous seen annotations.

Method signatures and docstrings:
- def __init__(self, tag_dictionary, tagset_size: int, init_from_state_dict: bool) -> None: Initialize the Conditional Random Field. :param tag_dictionary: tag dictionary in order to find ID for start and stop tags :param tagset_size: number of tag from tag dictionary :param init_from_state_dict: whether we load pretrained model from state dict
- def forward(self, features: torch.Tensor) -> torch.Tensor: Forward propagation of Conditional Random Field. :param features: output from RNN / Linear layer in shape (batch size, seq len, hidden size) :return: CRF scores (emission scores for each token + transitions prob from previous state) in shape (batch_size, seq len, tagset size, tagset size)

<|skeleton|>
class CRF:
    """Conditional Random Field. Conditional Random Field Implementation according to sgrvinod (https://github.com/sgrvinod). Classifier which predicts single tag / class / label for given word based on not just the word, but also on previous seen annotations."""

    def __init__(self, tag_dictionary, tagset_size: int, init_from_state_dict: bool) -> None:
        """Initialize the Conditional Random Field. :param tag_dictionary: tag dictionary in order to find ID for start and stop tags :param tagset_size: number of tag from tag dictionary :param init_from_state_dict: whether we load pretrained model from state dict"""
        <|body_0|>

    def forward(self, features: torch.Tensor) -> torch.Tensor:
        """Forward propagation of Conditional Random Field. :param features: output from RNN / Linear layer in shape (batch size, seq len, hidden size) :return: CRF scores (emission scores for each token + transitions prob from previous state) in shape (batch_size, seq len, tagset size, tagset size)"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        super().__init__()
        self.tagset_size = tagset_size
        self.transitions = torch.nn.Parameter(torch.randn(tagset_size, tagset_size))
        if not init_from_state_dict:
            self.transitions.detach()[tag_dictionary.get_idx_for_item(START_TAG), :] = -10000
            self.transitions.detach()[:, tag_dictionary.get_idx_for_item(STOP_TAG)] = -10000
        self.to(flair.device)
<|end_body_0|>

<|body_start_1|>
        batch_size, seq_len = features.size()[:2]
        emission_scores = features
        emission_scores = emission_scores.unsqueeze(-1).expand(batch_size, seq_len, self.tagset_size, self.tagset_size)
        crf_scores = emission_scores + self.transitions.unsqueeze(0).unsqueeze(0)
        return crf_scores
<|end_body_1|>

Solution:
class CRF:
    """Conditional Random Field. Conditional Random Field Implementation according to sgrvinod (https://github.com/sgrvinod). Classifier which predicts single tag / class / label for given word based on not just the word, but also on previous seen annotations."""

    def __init__(self, tag_dictionary, tagset_size: int, init_from_state_dict: bool) -> None:
        """Initialize the Conditional Random Field. :param tag_dictionary: tag dictionary in order to find ID for start and stop tags :param tagset_size: number of tag from tag dictionary :param init_from_state_dict: whether we load pretrained model from state dict"""
        super().__init__()
        self.tagset_size = tagset_size
        self.transitions = torch.nn.Parameter(torch.randn(tagset_size, tagset_size))
        if not init_from_state_dict:
            self.transitions.detach()[tag_dictionary.get_idx_for_item(START_TAG), :] = -10000
            self.transitions.detach()[:, tag_dictionary.get_idx_for_item(STOP_TAG)] = -10000
        self.to(flair.device)

    def forward(self, features: torch.Tensor) -> torch.Tensor:
        """Forward propagation of Conditional Random Field. :param features: output from RNN / Linear layer in shape (batch size, seq len, hidden size) :return: CRF scores (emission scores for each token + transitions prob from previous state) in shape (batch_size, seq len, tagset size, tagset size)"""
        batch_size, seq_len = features.size()[:2]
        emission_scores = features
        emission_scores = emission_scores.unsqueeze(-1).expand(batch_size, seq_len, self.tagset_size, self.tagset_size)
        crf_scores = emission_scores + self.transitions.unsqueeze(0).unsqueeze(0)
        return crf_scores


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

Class description:
Implement the NCNNManager class.

Method signatures and docstrings:
- def build_wrapper(cls, backend_files: Sequence[str], device: str='cpu', input_names: Optional[Sequence[str]]=None, output_names: Optional[Sequence[str]]=None, deploy_cfg: Optional[Any]=None, **kwargs): Build the wrapper for the backend model. Args: backend_files (Sequence[str]): Backend files. device (str, optional): The device info. Defaults to 'cpu'. input_names (Optional[Sequence[str]], optional): input names. Defaults to None. output_names (Optional[Sequence[str]], optional): output names. Defaults to None. deploy_cfg (Optional[Any], optional): The deploy config. Defaults to None.
- def is_available(cls, with_custom_ops: bool=False) -> bool: Check whether backend is installed. Args: with_custom_ops (bool): check custom ops exists. Returns: bool: True if backend package is installed.
- def get_version(cls) -> str: Get the version of the backend.
- def check_env(cls, log_callback: Callable=lambda _: _) -> str: Check current environment. Returns: str: Info about the environment.
- def to_backend(cls, ir_files: Sequence[str], work_dir: str, log_level: int=logging.INFO, device: str='cpu', **kwargs) -> Sequence[str]: Convert intermediate representation to given backend. Args: ir_files (Sequence[str]): The intermediate representation files. work_dir (str): The work directory, backend files and logs should be saved in this directory. log_level (int, optional): The log level. Defaults to logging.INFO. device (str, optional): The device type. Defaults to 'cpu'. Returns: Sequence[str]: Backend files.

Implement the Python class `NCNNManager` described below.

Class description:
Implement the NCNNManager class.

Method signatures and docstrings:
- def build_wrapper(cls, backend_files: Sequence[str], device: str='cpu', input_names: Optional[Sequence[str]]=None, output_names: Optional[Sequence[str]]=None, deploy_cfg: Optional[Any]=None, **kwargs): Build the wrapper for the backend model. Args: backend_files (Sequence[str]): Backend files. device (str, optional): The device info. Defaults to 'cpu'. input_names (Optional[Sequence[str]], optional): input names. Defaults to None. output_names (Optional[Sequence[str]], optional): output names. Defaults to None. deploy_cfg (Optional[Any], optional): The deploy config. Defaults to None.
- def is_available(cls, with_custom_ops: bool=False) -> bool: Check whether backend is installed. Args: with_custom_ops (bool): check custom ops exists. Returns: bool: True if backend package is installed.
- def get_version(cls) -> str: Get the version of the backend.
- def check_env(cls, log_callback: Callable=lambda _: _) -> str: Check current environment. Returns: str: Info about the environment.
- def to_backend(cls, ir_files: Sequence[str], work_dir: str, log_level: int=logging.INFO, device: str='cpu', **kwargs) -> Sequence[str]: Convert intermediate representation to given backend. Args: ir_files (Sequence[str]): The intermediate representation files. work_dir (str): The work directory, backend files and logs should be saved in this directory. log_level (int, optional): The log level. Defaults to logging.INFO. device (str, optional): The device type. Defaults to 'cpu'. Returns: Sequence[str]: Backend files.

<|skeleton|>
class NCNNManager:

    def build_wrapper(cls, backend_files: Sequence[str], device: str='cpu', input_names: Optional[Sequence[str]]=None, output_names: Optional[Sequence[str]]=None, deploy_cfg: Optional[Any]=None, **kwargs):
        """Build the wrapper for the backend model. Args: backend_files (Sequence[str]): Backend files. device (str, optional): The device info. Defaults to 'cpu'. input_names (Optional[Sequence[str]], optional): input names. Defaults to None. output_names (Optional[Sequence[str]], optional): output names. Defaults to None. deploy_cfg (Optional[Any], optional): The deploy config. Defaults to None."""
        <|body_0|>

    def is_available(cls, with_custom_ops: bool=False) -> bool:
        """Check whether backend is installed. Args: with_custom_ops (bool): check custom ops exists. Returns: bool: True if backend package is installed."""
        <|body_1|>

    def get_version(cls) -> str:
        """Get the version of the backend."""
        <|body_2|>

    def check_env(cls, log_callback: Callable=lambda _: _) -> str:
        """Check current environment. Returns: str: Info about the environment."""
        <|body_3|>

    def to_backend(cls, ir_files: Sequence[str], work_dir: str, log_level: int=logging.INFO, device: str='cpu', **kwargs) -> Sequence[str]:
        """Convert intermediate representation to given backend. Args: ir_files (Sequence[str]): The intermediate representation files. work_dir (str): The work directory, backend files and logs should be saved in this directory. log_level (int, optional): The log level. Defaults to logging.INFO. device (str, optional): The device type. Defaults to 'cpu'. Returns: Sequence[str]: Backend files."""
        <|body_4|>

<|end_skeleton|>

<|body_start_0|>
        from .wrapper import NCNNWrapper
        if deploy_cfg:
            backend_config = get_backend_config(deploy_cfg)
            use_vulkan = backend_config.get('use_vulkan', False)
        else:
            use_vulkan = False
        return NCNNWrapper(param_file=backend_files[0], bin_file=backend_files[1], output_names=output_names, use_vulkan=use_vulkan)
<|end_body_0|>

<|body_start_1|>
        import importlib
        from .init_plugins import get_onnx2ncnn_path, get_ops_path
        has_pyncnn = importlib.util.find_spec('ncnn') is not None
        onnx2ncnn = get_onnx2ncnn_path()
        ret = has_pyncnn and onnx2ncnn is not None
        if ret and with_custom_ops:
            has_pyncnn_ext = importlib.util.find_spec('mmdeploy.backend.ncnn.ncnn_ext') is not None
            op_path = get_ops_path()
            custom_ops_exist = osp.exists(op_path)
            ret = ret and has_pyncnn_ext and custom_ops_exist
        return ret
<|end_body_1|>

<|body_start_2|>
        if not cls.is_available():
            return 'None'
        else:
            import pkg_resources
            try:
                return pkg_resources.get_distribution('ncnn').version
            except Exception:
                return 'None'
<|end_body_2|>

<|body_start_3|>
        info = super().check_env(log_callback=log_callback)
        available = cls.is_available()
        ops_available = cls.is_available(with_custom_ops=True)
        ops_available = 'Available' if ops_available else 'NotAvailable'
        if available:
            ops_info = f'ncnn custom ops:\t{ops_available}'
            log_callback(ops_info)
            info = f'{info}\n{ops_info}'
        return info
<|end_body_3|>

<|body_start_4|>
        logger = get_root_logger()
        from . import is_available
        if not is_available():
            logger.error('ncnn support is not available, please make sure:\n1) `mmdeploy_onnx2ncnn` existed in `PATH`\n2) python import ncnn success')
            sys.exit(1)
        from mmdeploy.apis.ncnn import get_output_model_file
        from .onnx2ncnn import from_onnx
        backend_files = []
        for onnx_path in ir_files:
            model_param_path, model_bin_path = get_output_model_file(onnx_path, work_dir)
            onnx_name = osp.splitext(osp.split(onnx_path)[1])[0]
            from_onnx(onnx_path, osp.join(work_dir, onnx_name))
            backend_files += [model_param_path, model_bin_path]
        return backend_files
<|end_body_4|>

Solution:
class NCNNManager:
    def build_wrapper(cls, backend_files: Sequence[str], device: str='cpu', input_names: Optional[Sequence[str]]=None, output_names: Optional[Sequence[str]]=None, deploy_cfg: Optional[Any]=None, **kwargs):
        """Build the wrapper for the backend model. Args: backend_files (Sequence[str]): Backend files. device (str, optional): The device info. Defaults to 'cpu'. input_names (Optional[Sequence[str]], optional): input names. Defaults to None. output_names (Optional[Sequence[str]], optional): output names. Defaults to None. deploy_cfg (Optional[Any], optional): The deploy config. Defaults to None."""
        from .wrapper import NCNNWrapper
        if deploy_cfg:
            backend_config = get_backend_config(deploy_cfg)
            use_vulkan = backend_config.get('use_vulkan', False)
        else:
            use_vulkan = False
        return NCNNWrapper(param_file=backend_files[0], bin_file=backend_files[1], output_names=output_names, use_vulkan=use_vulkan)

    def is_available(cls, with_custom_ops: bool=False) -> bool:
        """Check whether backend is installed. Args: with_custom_ops (bool): check custom ops exists. Returns: bool: True if backend package is installed."""
        import importlib
        from .init_plugins import get_onnx2ncnn_path, get_ops_path
        has_pyncnn = importlib.util.find_spec('ncnn') is not None
        onnx2ncnn = get_onnx2ncnn_path()
        ret = has_pyncnn and onnx2ncnn is not None
        if ret and with_custom_ops:
            has_pyncnn_ext = importlib.util.find_spec('mmdeploy.backend.ncnn.ncnn_ext') is not None
            op_path = get_ops_path()
            custom_ops_exist = osp.exists(op_path)
            ret = ret and has_pyncnn_ext and custom_ops_exist
        return ret

    def get_version(cls) -> str:
        """Get the version of the backend."""
        if not cls.is_available():
            return 'None'
        else:
            import pkg_resources
            try:
                return pkg_resources.get_distribution('ncnn').version
            except Exception:
                return 'None'

    def check_env(cls, log_callback: Callable=lambda _: _) -> str:
        """Check current environment. Returns: str: Info about the environment."""
        info = super().check_env(log_callback=log_callback)
        available = cls.is_available()
        ops_available = cls.is_available(with_custom_ops=True)
        ops_available = 'Available' if ops_available else 'NotAvailable'
        if available:
            ops_info = f'ncnn custom ops:\t{ops_available}'
            log_callback(ops_info)
            info = f'{info}\n{ops_info}'
        return info

    def to_backend(cls, ir_files: Sequence[str], work_dir: str, log_level: int=logging.INFO, device: str='cpu', **kwargs) -> Sequence[str]:
        """Convert intermediate representation to given backend. Args: ir_files (Sequence[str]): The intermediate representation files. work_dir (str): The work directory, backend files and logs should be saved in this directory. log_level (int, optional): The log level. Defaults to logging.INFO. device (str, optional): The device type. Defaults to 'cpu'. Returns: Sequence[str]: Backend files."""
        logger = get_root_logger()
        from . import is_available
        if not is_available():
            logger.error('ncnn support is not available, please make sure:\n1) `mmdeploy_onnx2ncnn` existed in `PATH`\n2) python import ncnn success')
            sys.exit(1)
        from mmdeploy.apis.ncnn import get_output_model_file
        from .onnx2ncnn import from_onnx
        backend_files = []
        for onnx_path in ir_files:
            model_param_path, model_bin_path = get_output_model_file(onnx_path, work_dir)
            onnx_name = osp.splitext(osp.split(onnx_path)[1])[0]
            from_onnx(onnx_path, osp.join(work_dir, onnx_name))
            backend_files += [model_param_path, model_bin_path]
        return backend_files


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

Class description:
Implement the mainTest class.

Method signatures and docstrings:
- def add_case(caseName='testCase', rule='case*.py'): 作用：加载所有测试用例 :param caseName: :param rule: :return:
- def run_case(self, allcase, reportName='reports'): 作用：执行所有的用例，并把执行结果写入HTML测试报告中 :param all_case: :param reportName: :return:

Implement the Python class `mainTest` described below.

Class description:
Implement the mainTest class.

Method signatures and docstrings:
- def add_case(caseName='testCase', rule='case*.py'): 作用：加载所有测试用例 :param caseName: :param rule: :return:
- def run_case(self, allcase, reportName='reports'): 作用：执行所有的用例，并把执行结果写入HTML测试报告中 :param all_case: :param reportName: :return:

<|skeleton|>
class mainTest:

    def add_case(caseName='testCase', rule='case*.py'):
        """作用：加载所有测试用例 :param caseName: :param rule: :return:"""
        <|body_0|>

    def run_case(self, allcase, reportName='reports'):
        """作用：执行所有的用例，并把执行结果写入HTML测试报告中 :param all_case: :param reportName: :return:"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        case_path = os.path.join(os.getcwd(), caseName)
        if not os.path.exists(case_path):
            os.mkdir(case_path)
        testcase = unittest.TestSuite()
        discover = unittest.defaultTestLoader.discover(case_path, pattern=rule, top_level_dir=None)
        print(discover)
        for test_suite in discover:
            for test_case in test_suite:
                print(test_case)
                testcase.addTests(test_case)
        return testcase
<|end_body_0|>

<|body_start_1|>
        now = time.strftime('%Y_%m_%d_%H_%S')
        report_path = os.path.join(cur_path, reportName)
        if not os.path.exists(report_path):
            os.mkdir(report_path)
        report_abspath = os.path.join(report_path, now + '17网校直播Android测试报告.html')
        with open(report_abspath, 'wb') as fp:
            runner = HTMLTestRunner.HTMLTestRunner(stream=fp, title='17网校直播Android测试报告', description='用例执行情况')
            runner.run(allcase)
<|end_body_1|>

Solution:
class mainTest:
    def add_case(caseName='testCase', rule='case*.py'):
        """作用：加载所有测试用例 :param caseName: :param rule: :return:"""
        case_path = os.path.join(os.getcwd(), caseName)
        if not os.path.exists(case_path):
            os.mkdir(case_path)
        testcase = unittest.TestSuite()
        discover = unittest.defaultTestLoader.discover(case_path, pattern=rule, top_level_dir=None)
        print(discover)
        for test_suite in discover:
            for test_case in test_suite:
                print(test_case)
                testcase.addTests(test_case)
        return testcase

    def run_case(self, allcase, reportName='reports'):
        """作用：执行所有的用例，并把执行结果写入HTML测试报告中 :param all_case: :param reportName: :return:"""
        now = time.strftime('%Y_%m_%d_%H_%S')
        report_path = os.path.join(cur_path, reportName)
        if not os.path.exists(report_path):
            os.mkdir(report_path)
        report_abspath = os.path.join(report_path, now + '17网校直播Android测试报告.html')
        with open(report_abspath, 'wb') as fp:
            runner = HTMLTestRunner.HTMLTestRunner(stream=fp, title='17网校直播Android测试报告', description='用例执行情况')
            runner.run(allcase)


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

Class description:
Forrester Function.

Method signatures and docstrings:
- def __init__(self): Constructor.
- def cost(self, x): Cost function.

Implement the Python class `Forrester` described below.

Class description:
Forrester Function.

Method signatures and docstrings:
- def __init__(self): Constructor.
- def cost(self, x): Cost function.

<|skeleton|>
class Forrester:
    """Forrester Function."""

    def __init__(self):
        """Constructor."""
        <|body_0|>

    def cost(self, x):
        """Cost function."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.min = np.array([np.nan])
        self.value = np.nan
        self.domain = np.array([[0.0, 1.0]])
        self.n = 1
        self.smooth = True
        self.info = [True, False, False]
        self.latex_name = 'Forrester Function'
        self.latex_type = 'Many Local Minima'
        self.latex_cost = '\\[ f(x) = (6x - 2)^2 \\sin(12x - 4) \\]'
        self.latex_desc = 'This is a simple one-dimensional test function. '
<|end_body_0|>

<|body_start_1|>
        c = np.zeros(x.shape[1:])
        c = np.sin(12 * x[0] - 4) * (6 * x[0] - 2) ** 2
        return c
<|end_body_1|>

Solution:
class Forrester:
    """Forrester Function."""

    def __init__(self):
        """Constructor."""
        self.min = np.array([np.nan])
        self.value = np.nan
        self.domain = np.array([[0.0, 1.0]])
        self.n = 1
        self.smooth = True
        self.info = [True, False, False]
        self.latex_name = 'Forrester Function'
        self.latex_type = 'Many Local Minima'
        self.latex_cost = '\\[ f(x) = (6x - 2)^2 \\sin(12x - 4) \\]'
        self.latex_desc = 'This is a simple one-dimensional test function. '

    def cost(self, x):
        """Cost function."""
        c = np.zeros(x.shape[1:])
        c = np.sin(12 * x[0] - 4) * (6 * x[0] - 2) ** 2
        return c