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

Class description:
A Metric file. Because a metric can be viewed from the web, we can place it in the /static/ directory. However, we don't want to copy the file (too big) so we instead provide a symlink to its original path. The static_path argument is a path to the place in the /static/ directory where the symlink sits.

Method signatures and docstrings:
- def create_static_path(self): Creates a symbolic link to the metric from the static directory, where it can be served to the user. If the link already exists, this function deletes the previous link and replaces it with a new one.
- def remove_static_path(self): Deletes a the symbolic link associated with this Metric.

Implement the Python class `Metric` described below.

Class description:
A Metric file. Because a metric can be viewed from the web, we can place it in the /static/ directory. However, we don't want to copy the file (too big) so we instead provide a symlink to its original path. The static_path argument is a path to the place in the /static/ directory where the symlink sits.

Method signatures and docstrings:
- def create_static_path(self): Creates a symbolic link to the metric from the static directory, where it can be served to the user. If the link already exists, this function deletes the previous link and replaces it with a new one.
- def remove_static_path(self): Deletes a the symbolic link associated with this Metric.

<|skeleton|>
class Metric:
    """A Metric file. Because a metric can be viewed from the web, we can place it in the /static/ directory. However, we don't want to copy the file (too big) so we instead provide a symlink to its original path. The static_path argument is a path to the place in the /static/ directory where the symlink sits."""

    def create_static_path(self):
        """Creates a symbolic link to the metric from the static directory, where it can be served to the user. If the link already exists, this function deletes the previous link and replaces it with a new one."""
        <|body_0|>

    def remove_static_path(self):
        """Deletes a the symbolic link associated with this Metric."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        if not (self.project and self.analysis):
            return
        dest_path = join(settings.STATIC_ROOT, settings.STATIC_METRIC_LOCATION, self.project.name, self.analysis.name)
        dest_link = join(dest_path, self.name)
        source = join(self.project.path, settings.PROCESSED_DIR_NAME, self.analysis.name, settings.RESULTS_DIR_NAME, self.name)
        if exists(dest_link):
            unlink(dest_link)
        if not exists(dest_path):
            makedirs(dest_path)
        symlink(source, dest_link)
        self.static_path = dest_link
        self.save()
<|end_body_0|>

<|body_start_1|>
        if not self.static_path:
            return
        analysis_path, name = split(self.static_path)
        project_path = dirname(analysis_path)
        if exists(self.static_path):
            unlink(self.static_path)
        if not listdir(analysis_path):
            rmdir(analysis_path)
        if not listdir(project_path):
            rmdir(project_path)
<|end_body_1|>

Solution:
class Metric:
    """A Metric file. Because a metric can be viewed from the web, we can place it in the /static/ directory. However, we don't want to copy the file (too big) so we instead provide a symlink to its original path. The static_path argument is a path to the place in the /static/ directory where the symlink sits."""

    def create_static_path(self):
        """Creates a symbolic link to the metric from the static directory, where it can be served to the user. If the link already exists, this function deletes the previous link and replaces it with a new one."""
        if not (self.project and self.analysis):
            return
        dest_path = join(settings.STATIC_ROOT, settings.STATIC_METRIC_LOCATION, self.project.name, self.analysis.name)
        dest_link = join(dest_path, self.name)
        source = join(self.project.path, settings.PROCESSED_DIR_NAME, self.analysis.name, settings.RESULTS_DIR_NAME, self.name)
        if exists(dest_link):
            unlink(dest_link)
        if not exists(dest_path):
            makedirs(dest_path)
        symlink(source, dest_link)
        self.static_path = dest_link
        self.save()

    def remove_static_path(self):
        """Deletes a the symbolic link associated with this Metric."""
        if not self.static_path:
            return
        analysis_path, name = split(self.static_path)
        project_path = dirname(analysis_path)
        if exists(self.static_path):
            unlink(self.static_path)
        if not listdir(analysis_path):
            rmdir(analysis_path)
        if not listdir(project_path):
            rmdir(project_path)


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

Class description:
Command to seed the database with all available resource files

Method signatures and docstrings:
- def run(self, *, no_staleness=False): Create the new log entry
- def addStalenessPeriods(self): Add the staleness periods
- def getListName(self, filename): Return the list name for the given file

Implement the Python class `Seed` described below.

Class description:
Command to seed the database with all available resource files

Method signatures and docstrings:
- def run(self, *, no_staleness=False): Create the new log entry
- def addStalenessPeriods(self): Add the staleness periods
- def getListName(self, filename): Return the list name for the given file

<|skeleton|>
class Seed:
    """Command to seed the database with all available resource files"""

    def run(self, *, no_staleness=False):
        """Create the new log entry"""
        <|body_0|>

    def addStalenessPeriods(self):
        """Add the staleness periods"""
        <|body_1|>

    def getListName(self, filename):
        """Return the list name for the given file"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        if not no_staleness:
            self.addStalenessPeriods()
        importer = ImportCmd()
        for filename in glob.glob(os.path.join(EGG_DIR, '*.json')):
            importer.run(filename, listName=self.getListName(filename))
<|end_body_0|>

<|body_start_1|>
        previousPeriod = None
        for days in [180, 90, 30, 14, 7]:
            if previousPeriod is not None:
                period = StalenessPeriod(days=days, next=previousPeriod)
            else:
                period = StalenessPeriod(days=days)
            previousPeriod = period
            server.db.session.add(period)
        period = StalenessPeriod(days=3, next=previousPeriod, first=True)
        server.db.session.add(period)
        server.db.session.commit()
<|end_body_1|>

<|body_start_2|>
        fullPath = os.path.abspath(filename)
        basename = os.path.basename(fullPath)
        filenameWithoutExtension = os.path.splitext(basename)[0]
        pieces = filenameWithoutExtension.split('_')
        capitalizedPieces = [piece.capitalize() for piece in pieces]
        return ' '.join(capitalizedPieces)
<|end_body_2|>

Solution:
class Seed:
    """Command to seed the database with all available resource files"""

    def run(self, *, no_staleness=False):
        """Create the new log entry"""
        if not no_staleness:
            self.addStalenessPeriods()
        importer = ImportCmd()
        for filename in glob.glob(os.path.join(EGG_DIR, '*.json')):
            importer.run(filename, listName=self.getListName(filename))

    def addStalenessPeriods(self):
        """Add the staleness periods"""
        previousPeriod = None
        for days in [180, 90, 30, 14, 7]:
            if previousPeriod is not None:
                period = StalenessPeriod(days=days, next=previousPeriod)
            else:
                period = StalenessPeriod(days=days)
            previousPeriod = period
            server.db.session.add(period)
        period = StalenessPeriod(days=3, next=previousPeriod, first=True)
        server.db.session.add(period)
        server.db.session.commit()

    def getListName(self, filename):
        """Return the list name for the given file"""
        fullPath = os.path.abspath(filename)
        basename = os.path.basename(fullPath)
        filenameWithoutExtension = os.path.splitext(basename)[0]
        pieces = filenameWithoutExtension.split('_')
        capitalizedPieces = [piece.capitalize() for piece in pieces]
        return ' '.join(capitalizedPieces)


post

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

Class description:
This class deals with registration get > loads a registration page post > analyses datas to try to create a new user and profile

Method signatures and docstrings:
- def get(self, request): manages the get request for the register page
- def post(self, request): manages the post request for the register page : get datas in order to try to create a new user

Implement the Python class `RegisterView` described below.

Class description:
This class deals with registration get > loads a registration page post > analyses datas to try to create a new user and profile

Method signatures and docstrings:
- def get(self, request): manages the get request for the register page
- def post(self, request): manages the post request for the register page : get datas in order to try to create a new user

<|skeleton|>
class RegisterView:
    """This class deals with registration get > loads a registration page post > analyses datas to try to create a new user and profile"""

    def get(self, request):
        """manages the get request for the register page"""
        <|body_0|>

    def post(self, request):
        """manages the post request for the register page : get datas in order to try to create a new user"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        if request.user.is_authenticated:
            return redirect('research:index')
        us_form = UserForm()
        context = {'us_form': us_form}
        return render(request, 'user/register.html', context)
<|end_body_0|>

<|body_start_1|>
        us_form = UserForm(request.POST)
        if us_form.is_valid():
            name, password = (us_form.cleaned_data['username'], us_form.cleaned_data['password'])
            success, message = add_new_user(name, password)
            messages.info(request, message)
            if success:
                return redirect('user:connection')
            return redirect('user:register')
        return HttpResponse('Problème dans le formulaire !')
<|end_body_1|>

Solution:
class RegisterView:
    """This class deals with registration get > loads a registration page post > analyses datas to try to create a new user and profile"""

    def get(self, request):
        """manages the get request for the register page"""
        if request.user.is_authenticated:
            return redirect('research:index')
        us_form = UserForm()
        context = {'us_form': us_form}
        return render(request, 'user/register.html', context)

    def post(self, request):
        """manages the post request for the register page : get datas in order to try to create a new user"""
        us_form = UserForm(request.POST)
        if us_form.is_valid():
            name, password = (us_form.cleaned_data['username'], us_form.cleaned_data['password'])
            success, message = add_new_user(name, password)
            messages.info(request, message)
            if success:
                return redirect('user:connection')
            return redirect('user:register')
        return HttpResponse('Problème dans le formulaire !')


report

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

Class description:
Implement the Reporter class.

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

Implement the Python class `Reporter` described below.

Class description:
Implement the Reporter class.

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

<|skeleton|>
class Reporter:

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

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

<|end_skeleton|>

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

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

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

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


update

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

Class description:
Class that represents Budget Limit in system.

Method signatures and docstrings:
- async def get_by_id(cls, limit_id): Return queried budget limit by provided id.
- async def get_user_limits(cls, user_id): Return queried user`s budget limits.
- async def create(cls, user_id, category_id, amount): Create a new budget limit in database.
- async def update(cls, limit_id, amount): Update budget limit instance in database.
- async def delete(cls, limit_id): Delete budget limit by provided id.

Implement the Python class `Limit` described below.

Class description:
Class that represents Budget Limit in system.

Method signatures and docstrings:
- async def get_by_id(cls, limit_id): Return queried budget limit by provided id.
- async def get_user_limits(cls, user_id): Return queried user`s budget limits.
- async def create(cls, user_id, category_id, amount): Create a new budget limit in database.
- async def update(cls, limit_id, amount): Update budget limit instance in database.
- async def delete(cls, limit_id): Delete budget limit by provided id.

<|skeleton|>
class Limit:
    """Class that represents Budget Limit in system."""

    async def get_by_id(cls, limit_id):
        """Return queried budget limit by provided id."""
        <|body_0|>

    async def get_user_limits(cls, user_id):
        """Return queried user`s budget limits."""
        <|body_1|>

    async def create(cls, user_id, category_id, amount):
        """Create a new budget limit in database."""
        <|body_2|>

    async def update(cls, limit_id, amount):
        """Update budget limit instance in database."""
        <|body_3|>

    async def delete(cls, limit_id):
        """Delete budget limit by provided id."""
        <|body_4|>

<|end_skeleton|>

<|body_start_0|>
        try:
            limit = await super().get(limit_id)
        except SQLAlchemyError as err:
            LOGGER.error('Could not retrieve budget limit by id=%s. Error: %s', limit_id, err)
            raise DatabaseError('Failed to retrieve requested budget limit.')
        if not limit:
            raise DBNoResultFoundError('The requested budget limit does not exist.')
        return limit
<|end_body_0|>

<|body_start_1|>
        try:
            limits = await db.select([cls.id, cast(cls.amount, db.String).label('balance'), MCCCategory.name, MCCCategory.info]).select_from(cls.join(MCCCategory)).where(cls.user_id == user_id).gino.all()
        except SQLAlchemyError as err:
            LOGGER.error('Could not retrieve budget limits for user=%s. Error: %s', user_id, err)
            raise DatabaseError('Failed to retrieve budget limits for requested user.')
        return [dict(limit) for limit in limits]
<|end_body_1|>

<|body_start_2|>
        try:
            return await super().create(user_id=user_id, category_id=category_id, amount=amount)
        except exceptions.UniqueViolationError:
            raise DatabaseError('A limit with such category for requested user already exists.')
        except SQLAlchemyError as err:
            LOGGER.error('Could not create limit with category=%s for user=%s. Error: %s', category_id, user_id, err)
            raise DatabaseError('Failed to create limit budget for requested user.')
<|end_body_2|>

<|body_start_3|>
        try:
            status, _ = await super().update.values(amount=amount).where(cls.id == limit_id).gino.status()
        except SQLAlchemyError as err:
            LOGGER.error('Could not update budget limit=%s. Error: %s', limit_id, err)
            raise DatabaseError('Failed to update budget limit.')
        updated = parse_status(status)
        if not updated:
            raise DatabaseError('The budget limit was not updated.')
<|end_body_3|>

<|body_start_4|>
        try:
            status, _ = await super().delete.where(cls.id == limit_id).gino.status()
        except SQLAlchemyError as err:
            LOGGER.error('Could not delete budget limit by id=%s. Error: %s', limit_id, err)
            raise DatabaseError('Failed to delete budget limit.')
        deleted = parse_status(status)
        if not deleted:
            raise DatabaseError('The budget category limit was not deleted.')
<|end_body_4|>

Solution:
class Limit:
    """Class that represents Budget Limit in system."""

    async def get_by_id(cls, limit_id):
        """Return queried budget limit by provided id."""
        try:
            limit = await super().get(limit_id)
        except SQLAlchemyError as err:
            LOGGER.error('Could not retrieve budget limit by id=%s. Error: %s', limit_id, err)
            raise DatabaseError('Failed to retrieve requested budget limit.')
        if not limit:
            raise DBNoResultFoundError('The requested budget limit does not exist.')
        return limit

    async def get_user_limits(cls, user_id):
        """Return queried user`s budget limits."""
        try:
            limits = await db.select([cls.id, cast(cls.amount, db.String).label('balance'), MCCCategory.name, MCCCategory.info]).select_from(cls.join(MCCCategory)).where(cls.user_id == user_id).gino.all()
        except SQLAlchemyError as err:
            LOGGER.error('Could not retrieve budget limits for user=%s. Error: %s', user_id, err)
            raise DatabaseError('Failed to retrieve budget limits for requested user.')
        return [dict(limit) for limit in limits]

    async def create(cls, user_id, category_id, amount):
        """Create a new budget limit in database."""
        try:
            return await super().create(user_id=user_id, category_id=category_id, amount=amount)
        except exceptions.UniqueViolationError:
            raise DatabaseError('A limit with such category for requested user already exists.')
        except SQLAlchemyError as err:
            LOGGER.error('Could not create limit with category=%s for user=%s. Error: %s', category_id, user_id, err)
            raise DatabaseError('Failed to create limit budget for requested user.')

    async def update(cls, limit_id, amount):
        """Update budget limit instance in database."""
        try:
            status, _ = await super().update.values(amount=amount).where(cls.id == limit_id).gino.status()
        except SQLAlchemyError as err:
            LOGGER.error('Could not update budget limit=%s. Error: %s', limit_id, err)
            raise DatabaseError('Failed to update budget limit.')
        updated = parse_status(status)
        if not updated:
            raise DatabaseError('The budget limit was not updated.')

    async def delete(cls, limit_id):
        """Delete budget limit by provided id."""
        try:
            status, _ = await super().delete.where(cls.id == limit_id).gino.status()
        except SQLAlchemyError as err:
            LOGGER.error('Could not delete budget limit by id=%s. Error: %s', limit_id, err)
            raise DatabaseError('Failed to delete budget limit.')
        deleted = parse_status(status)
        if not deleted:
            raise DatabaseError('The budget category limit was not deleted.')


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

Class description:
Implement the ScalableBoxActionSpace class.

Method signatures and docstrings:
- def __init__(self, shape: Union[int, np.ndarray], low: Union[None, int, float, np.ndarray]=-np.inf, high: Union[None, int, float, np.ndarray]=np.inf, descriptions: Union[None, List, Dict]=None, default_action: np.ndarray=None, scale_action_space: bool=False, scaled_up_action_space_bounds: Dict={ModelMetadataKeys.LOW.value: -np.inf, ModelMetadataKeys.HIGH.value: np.inf}): This class extends BoxActionSpace and adds ability to scale the actions Args: shape (Union[int, np.ndarray]): int or array value of the shape of the action space low (Union[None, int, float, np.ndarray], optional): higher bound of the action space. Defaults to -np.inf. high (Union[None, int, float, np.ndarray], optional): higher bound of the action space. Defaults to np.inf. descriptions (Union[None, List, Dict], optional): description set for each action value. Defaults to None. default_action (np.ndarray, optional): default action value. Defaults to None. scale_action_space (bool, optional): boolean value to indicate if scaling needs to be done. Defaults to False. scaled_up_action_space_bo
- def scale_action_values(self, actions): Return the action space for the training algorithm Args: actions (list(float)): The list of actions that need to be scaled Returns: list(float): scaled/unscaled actions depending on the scale_action_space value set
- def _scale_value(self, action, min_old, max_old, min_new, max_new): Return the scaled action value from min_old,max_old to min_new,max_new Args: action (float): The action value to be scaled min_old (float): The minimum bound value before scaling max_old (float): The maximum bound value before scaling min_new (float): The minimum bound value after scaling max_new (float): The maximum bound value after scaling Returns: (float): scaled action value

Implement the Python class `ScalableBoxActionSpace` described below.

Class description:
Implement the ScalableBoxActionSpace class.

Method signatures and docstrings:
- def __init__(self, shape: Union[int, np.ndarray], low: Union[None, int, float, np.ndarray]=-np.inf, high: Union[None, int, float, np.ndarray]=np.inf, descriptions: Union[None, List, Dict]=None, default_action: np.ndarray=None, scale_action_space: bool=False, scaled_up_action_space_bounds: Dict={ModelMetadataKeys.LOW.value: -np.inf, ModelMetadataKeys.HIGH.value: np.inf}): This class extends BoxActionSpace and adds ability to scale the actions Args: shape (Union[int, np.ndarray]): int or array value of the shape of the action space low (Union[None, int, float, np.ndarray], optional): higher bound of the action space. Defaults to -np.inf. high (Union[None, int, float, np.ndarray], optional): higher bound of the action space. Defaults to np.inf. descriptions (Union[None, List, Dict], optional): description set for each action value. Defaults to None. default_action (np.ndarray, optional): default action value. Defaults to None. scale_action_space (bool, optional): boolean value to indicate if scaling needs to be done. Defaults to False. scaled_up_action_space_bo
- def scale_action_values(self, actions): Return the action space for the training algorithm Args: actions (list(float)): The list of actions that need to be scaled Returns: list(float): scaled/unscaled actions depending on the scale_action_space value set
- def _scale_value(self, action, min_old, max_old, min_new, max_new): Return the scaled action value from min_old,max_old to min_new,max_new Args: action (float): The action value to be scaled min_old (float): The minimum bound value before scaling max_old (float): The maximum bound value before scaling min_new (float): The minimum bound value after scaling max_new (float): The maximum bound value after scaling Returns: (float): scaled action value

<|skeleton|>
class ScalableBoxActionSpace:

    def __init__(self, shape: Union[int, np.ndarray], low: Union[None, int, float, np.ndarray]=-np.inf, high: Union[None, int, float, np.ndarray]=np.inf, descriptions: Union[None, List, Dict]=None, default_action: np.ndarray=None, scale_action_space: bool=False, scaled_up_action_space_bounds: Dict={ModelMetadataKeys.LOW.value: -np.inf, ModelMetadataKeys.HIGH.value: np.inf}):
        """This class extends BoxActionSpace and adds ability to scale the actions Args: shape (Union[int, np.ndarray]): int or array value of the shape of the action space low (Union[None, int, float, np.ndarray], optional): higher bound of the action space. Defaults to -np.inf. high (Union[None, int, float, np.ndarray], optional): higher bound of the action space. Defaults to np.inf. descriptions (Union[None, List, Dict], optional): description set for each action value. Defaults to None. default_action (np.ndarray, optional): default action value. Defaults to None. scale_action_space (bool, optional): boolean value to indicate if scaling needs to be done. Defaults to False. scaled_up_action_space_bo"""
        <|body_0|>

    def scale_action_values(self, actions):
        """Return the action space for the training algorithm Args: actions (list(float)): The list of actions that need to be scaled Returns: list(float): scaled/unscaled actions depending on the scale_action_space value set"""
        <|body_1|>

    def _scale_value(self, action, min_old, max_old, min_new, max_new):
        """Return the scaled action value from min_old,max_old to min_new,max_new Args: action (float): The action value to be scaled min_old (float): The minimum bound value before scaling max_old (float): The maximum bound value before scaling min_new (float): The minimum bound value after scaling max_new (float): The maximum bound value after scaling Returns: (float): scaled action value"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        super().__init__(shape, low, high, descriptions, default_action)
        self.scale_action_space = scale_action_space
        self.scaled_up_action_space_bounds = scaled_up_action_space_bounds
<|end_body_0|>

<|body_start_1|>
        if not self.scale_action_space:
            return actions
        scaled_actions = list()
        for action, low, high, scaled_low, scaled_high in zip(actions, self.low, self.high, self.scaled_up_action_space_bounds[ModelMetadataKeys.LOW.value], self.scaled_up_action_space_bounds[ModelMetadataKeys.HIGH.value]):
            scaled_actions.append(self._scale_value(action, low, high, scaled_low, scaled_high))
        return scaled_actions
<|end_body_1|>

<|body_start_2|>
        if max_old == min_old:
            log_and_exit('Unsupported minimum and maximum action space bounds for scaling values.                 min_old: {}; max_old: {}'.format(min_old, max_old), SIMAPP_SIMULATION_WORKER_EXCEPTION, SIMAPP_EVENT_ERROR_CODE_500)
        return (max_new - min_new) / (max_old - min_old) * (action - min_old) + min_new
<|end_body_2|>

Solution:
class ScalableBoxActionSpace:
    def __init__(self, shape: Union[int, np.ndarray], low: Union[None, int, float, np.ndarray]=-np.inf, high: Union[None, int, float, np.ndarray]=np.inf, descriptions: Union[None, List, Dict]=None, default_action: np.ndarray=None, scale_action_space: bool=False, scaled_up_action_space_bounds: Dict={ModelMetadataKeys.LOW.value: -np.inf, ModelMetadataKeys.HIGH.value: np.inf}):
        """This class extends BoxActionSpace and adds ability to scale the actions Args: shape (Union[int, np.ndarray]): int or array value of the shape of the action space low (Union[None, int, float, np.ndarray], optional): higher bound of the action space. Defaults to -np.inf. high (Union[None, int, float, np.ndarray], optional): higher bound of the action space. Defaults to np.inf. descriptions (Union[None, List, Dict], optional): description set for each action value. Defaults to None. default_action (np.ndarray, optional): default action value. Defaults to None. scale_action_space (bool, optional): boolean value to indicate if scaling needs to be done. Defaults to False. scaled_up_action_space_bo"""
        super().__init__(shape, low, high, descriptions, default_action)
        self.scale_action_space = scale_action_space
        self.scaled_up_action_space_bounds = scaled_up_action_space_bounds

    def scale_action_values(self, actions):
        """Return the action space for the training algorithm Args: actions (list(float)): The list of actions that need to be scaled Returns: list(float): scaled/unscaled actions depending on the scale_action_space value set"""
        if not self.scale_action_space:
            return actions
        scaled_actions = list()
        for action, low, high, scaled_low, scaled_high in zip(actions, self.low, self.high, self.scaled_up_action_space_bounds[ModelMetadataKeys.LOW.value], self.scaled_up_action_space_bounds[ModelMetadataKeys.HIGH.value]):
            scaled_actions.append(self._scale_value(action, low, high, scaled_low, scaled_high))
        return scaled_actions

    def _scale_value(self, action, min_old, max_old, min_new, max_new):
        """Return the scaled action value from min_old,max_old to min_new,max_new Args: action (float): The action value to be scaled min_old (float): The minimum bound value before scaling max_old (float): The maximum bound value before scaling min_new (float): The minimum bound value after scaling max_new (float): The maximum bound value after scaling Returns: (float): scaled action value"""
        if max_old == min_old:
            log_and_exit('Unsupported minimum and maximum action space bounds for scaling values.                 min_old: {}; max_old: {}'.format(min_old, max_old), SIMAPP_SIMULATION_WORKER_EXCEPTION, SIMAPP_EVENT_ERROR_CODE_500)
        return (max_new - min_new) / (max_old - min_old) * (action - min_old) + min_new


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

Class description:
Test conversion of global coordinates to geocentric cartesians. In this coordinate system, x and y are in the equitorial plane, and z is towards the poles.

Method signatures and docstrings:
- def test_basic(self): Test a (0, 0) coordinate conversion to geocentric cartesian. This is expected to give an x coordinate which is the semi-major axis of the globe defined in the global coordinate system.
- def test_north_pole(self): Test a (0, 90) coordinate conversion to geocentric cartesian, this being the north pole. This is expected to give an x coordinate which 0 and a z coordinate equivalent to the semi-major axis of the globe defined in the global coordinate system.
- def test_45_degrees_latitude(self): Test a (0, 45) coordinate conversion to geocentric cartesian. In this case the components of the semi-major axis of the globe defined in the global coordinate system should be shared between the resulting x and z coordinates.
- def test_45_degrees_longitude(self): Test a (45, 0) coordinate conversion to geocentric cartesian. In this case the components of the semi-major axis of the globe defined in the global coordinate system should be shared between the resulting x and y coordinates.
- def test_45_degrees_latitude_and_longitude(self): Test a (45, 45) coordinate conversion to geocentric cartesian. In this case the z component should be a cos(45) component of the semi-major axis of the globe defined in the global coordinate system. The x and y coordinates should be cos(45) components of the remaining cos(45) component of the semi-major axis.
- def test_negative_45_degrees_latitude_and_longitude(self): Test a (-45, -45) coordinate conversion to geocentric cartesian. In this case the x is expected to remain positive, whilst y and z become negative.

Implement the Python class `Test_geocentric_cartesian` described below.

Class description:
Test conversion of global coordinates to geocentric cartesians. In this coordinate system, x and y are in the equitorial plane, and z is towards the poles.

Method signatures and docstrings:
- def test_basic(self): Test a (0, 0) coordinate conversion to geocentric cartesian. This is expected to give an x coordinate which is the semi-major axis of the globe defined in the global coordinate system.
- def test_north_pole(self): Test a (0, 90) coordinate conversion to geocentric cartesian, this being the north pole. This is expected to give an x coordinate which 0 and a z coordinate equivalent to the semi-major axis of the globe defined in the global coordinate system.
- def test_45_degrees_latitude(self): Test a (0, 45) coordinate conversion to geocentric cartesian. In this case the components of the semi-major axis of the globe defined in the global coordinate system should be shared between the resulting x and z coordinates.
- def test_45_degrees_longitude(self): Test a (45, 0) coordinate conversion to geocentric cartesian. In this case the components of the semi-major axis of the globe defined in the global coordinate system should be shared between the resulting x and y coordinates.
- def test_45_degrees_latitude_and_longitude(self): Test a (45, 45) coordinate conversion to geocentric cartesian. In this case the z component should be a cos(45) component of the semi-major axis of the globe defined in the global coordinate system. The x and y coordinates should be cos(45) components of the remaining cos(45) component of the semi-major axis.
- def test_negative_45_degrees_latitude_and_longitude(self): Test a (-45, -45) coordinate conversion to geocentric cartesian. In this case the x is expected to remain positive, whilst y and z become negative.

<|skeleton|>
class Test_geocentric_cartesian:
    """Test conversion of global coordinates to geocentric cartesians. In this coordinate system, x and y are in the equitorial plane, and z is towards the poles."""

    def test_basic(self):
        """Test a (0, 0) coordinate conversion to geocentric cartesian. This is expected to give an x coordinate which is the semi-major axis of the globe defined in the global coordinate system."""
        <|body_0|>

    def test_north_pole(self):
        """Test a (0, 90) coordinate conversion to geocentric cartesian, this being the north pole. This is expected to give an x coordinate which 0 and a z coordinate equivalent to the semi-major axis of the globe defined in the global coordinate system."""
        <|body_1|>

    def test_45_degrees_latitude(self):
        """Test a (0, 45) coordinate conversion to geocentric cartesian. In this case the components of the semi-major axis of the globe defined in the global coordinate system should be shared between the resulting x and z coordinates."""
        <|body_2|>

    def test_45_degrees_longitude(self):
        """Test a (45, 0) coordinate conversion to geocentric cartesian. In this case the components of the semi-major axis of the globe defined in the global coordinate system should be shared between the resulting x and y coordinates."""
        <|body_3|>

    def test_45_degrees_latitude_and_longitude(self):
        """Test a (45, 45) coordinate conversion to geocentric cartesian. In this case the z component should be a cos(45) component of the semi-major axis of the globe defined in the global coordinate system. The x and y coordinates should be cos(45) components of the remaining cos(45) component of the semi-major axis."""
        <|body_4|>

    def test_negative_45_degrees_latitude_and_longitude(self):
        """Test a (-45, -45) coordinate conversion to geocentric cartesian. In this case the x is expected to remain positive, whilst y and z become negative."""
        <|body_5|>

<|end_skeleton|>

<|body_start_0|>
        plugin = NeighbourSelection()
        x_points = np.array([0])
        y_points = np.array([0])
        result = plugin.geocentric_cartesian(self.global_orography, x_points, y_points)
        radius = self.global_orography.coord_system().semi_major_axis
        expected = [[radius, 0, 0]]
        self.assertArrayAlmostEqual(result, expected)
<|end_body_0|>

<|body_start_1|>
        plugin = NeighbourSelection()
        x_points = np.array([0])
        y_points = np.array([90])
        result = plugin.geocentric_cartesian(self.global_orography, x_points, y_points)
        radius = self.global_orography.coord_system().semi_major_axis
        expected = [[0, 0, radius]]
        self.assertArrayAlmostEqual(result, expected)
<|end_body_1|>

<|body_start_2|>
        plugin = NeighbourSelection()
        x_points = np.array([0])
        y_points = np.array([45])
        result = plugin.geocentric_cartesian(self.global_orography, x_points, y_points)
        radius = self.global_orography.coord_system().semi_major_axis
        component = radius / np.sqrt(2.0)
        expected = [[component, 0, component]]
        self.assertArrayAlmostEqual(result, expected)
<|end_body_2|>

<|body_start_3|>
        plugin = NeighbourSelection()
        x_points = np.array([45])
        y_points = np.array([0])
        result = plugin.geocentric_cartesian(self.global_orography, x_points, y_points)
        radius = self.global_orography.coord_system().semi_major_axis
        component = radius / np.sqrt(2.0)
        expected = [[component, component, 0]]
        self.assertArrayAlmostEqual(result, expected)
<|end_body_3|>

<|body_start_4|>
        plugin = NeighbourSelection()
        x_points = np.array([45])
        y_points = np.array([45])
        result = plugin.geocentric_cartesian(self.global_orography, x_points, y_points)
        radius = self.global_orography.coord_system().semi_major_axis
        component = radius / np.sqrt(2.0)
        sub_component = component / np.sqrt(2.0)
        expected = [[sub_component, sub_component, component]]
        self.assertArrayAlmostEqual(result, expected)
<|end_body_4|>

<|body_start_5|>
        plugin = NeighbourSelection()
        x_points = np.array([-45])
        y_points = np.array([-45])
        result = plugin.geocentric_cartesian(self.global_orography, x_points, y_points)
        radius = self.global_orography.coord_system().semi_major_axis
        component = radius / np.sqrt(2.0)
        sub_component = component / np.sqrt(2.0)
        expected = [[sub_component, -sub_component, -component]]
        self.assertArrayAlmostEqual(result, expected)
<|end_body_5|>

Solution:
class Test_geocentric_cartesian:
    """Test conversion of global coordinates to geocentric cartesians. In this coordinate system, x and y are in the equitorial plane, and z is towards the poles."""

    def test_basic(self):
        """Test a (0, 0) coordinate conversion to geocentric cartesian. This is expected to give an x coordinate which is the semi-major axis of the globe defined in the global coordinate system."""
        plugin = NeighbourSelection()
        x_points = np.array([0])
        y_points = np.array([0])
        result = plugin.geocentric_cartesian(self.global_orography, x_points, y_points)
        radius = self.global_orography.coord_system().semi_major_axis
        expected = [[radius, 0, 0]]
        self.assertArrayAlmostEqual(result, expected)

    def test_north_pole(self):
        """Test a (0, 90) coordinate conversion to geocentric cartesian, this being the north pole. This is expected to give an x coordinate which 0 and a z coordinate equivalent to the semi-major axis of the globe defined in the global coordinate system."""
        plugin = NeighbourSelection()
        x_points = np.array([0])
        y_points = np.array([90])
        result = plugin.geocentric_cartesian(self.global_orography, x_points, y_points)
        radius = self.global_orography.coord_system().semi_major_axis
        expected = [[0, 0, radius]]
        self.assertArrayAlmostEqual(result, expected)

    def test_45_degrees_latitude(self):
        """Test a (0, 45) coordinate conversion to geocentric cartesian. In this case the components of the semi-major axis of the globe defined in the global coordinate system should be shared between the resulting x and z coordinates."""
        plugin = NeighbourSelection()
        x_points = np.array([0])
        y_points = np.array([45])
        result = plugin.geocentric_cartesian(self.global_orography, x_points, y_points)
        radius = self.global_orography.coord_system().semi_major_axis
        component = radius / np.sqrt(2.0)
        expected = [[component, 0, component]]
        self.assertArrayAlmostEqual(result, expected)

    def test_45_degrees_longitude(self):
        """Test a (45, 0) coordinate conversion to geocentric cartesian. In this case the components of the semi-major axis of the globe defined in the global coordinate system should be shared between the resulting x and y coordinates."""
        plugin = NeighbourSelection()
        x_points = np.array([45])
        y_points = np.array([0])
        result = plugin.geocentric_cartesian(self.global_orography, x_points, y_points)
        radius = self.global_orography.coord_system().semi_major_axis
        component = radius / np.sqrt(2.0)
        expected = [[component, component, 0]]
        self.assertArrayAlmostEqual(result, expected)

    def test_45_degrees_latitude_and_longitude(self):
        """Test a (45, 45) coordinate conversion to geocentric cartesian. In this case the z component should be a cos(45) component of the semi-major axis of the globe defined in the global coordinate system. The x and y coordinates should be cos(45) components of the remaining cos(45) component of the semi-major axis."""
        plugin = NeighbourSelection()
        x_points = np.array([45])
        y_points = np.array([45])
        result = plugin.geocentric_cartesian(self.global_orography, x_points, y_points)
        radius = self.global_orography.coord_system().semi_major_axis
        component = radius / np.sqrt(2.0)
        sub_component = component / np.sqrt(2.0)
        expected = [[sub_component, sub_component, component]]
        self.assertArrayAlmostEqual(result, expected)

    def test_negative_45_degrees_latitude_and_longitude(self):
        """Test a (-45, -45) coordinate conversion to geocentric cartesian. In this case the x is expected to remain positive, whilst y and z become negative."""
        plugin = NeighbourSelection()
        x_points = np.array([-45])
        y_points = np.array([-45])
        result = plugin.geocentric_cartesian(self.global_orography, x_points, y_points)
        radius = self.global_orography.coord_system().semi_major_axis
        component = radius / np.sqrt(2.0)
        sub_component = component / np.sqrt(2.0)
        expected = [[sub_component, -sub_component, -component]]
        self.assertArrayAlmostEqual(result, expected)


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

Class description:
Implement the MaxPool2DNaive class.

Method signatures and docstrings:
- def forward_npdl(self, X, **kwargs): Effectue la propagation avant d'une couche MaxPool2D Arguments: X {ndarray} -- Sortie de la couche précédente. Returns: ndarray -- Scores de la couche
- def backward_npdl(self, dA, **kwargs): Effectue la rétro-propagation. Arguments: dA {ndarray} -- Gradients de la loss par rapport aux sorties. Returns: ndarray -- Dérivée de la loss par rapport au input de la couche.

Implement the Python class `MaxPool2DNaive` described below.

Class description:
Implement the MaxPool2DNaive class.

Method signatures and docstrings:
- def forward_npdl(self, X, **kwargs): Effectue la propagation avant d'une couche MaxPool2D Arguments: X {ndarray} -- Sortie de la couche précédente. Returns: ndarray -- Scores de la couche
- def backward_npdl(self, dA, **kwargs): Effectue la rétro-propagation. Arguments: dA {ndarray} -- Gradients de la loss par rapport aux sorties. Returns: ndarray -- Dérivée de la loss par rapport au input de la couche.

<|skeleton|>
class MaxPool2DNaive:

    def forward_npdl(self, X, **kwargs):
        """Effectue la propagation avant d'une couche MaxPool2D Arguments: X {ndarray} -- Sortie de la couche précédente. Returns: ndarray -- Scores de la couche"""
        <|body_0|>

    def backward_npdl(self, dA, **kwargs):
        """Effectue la rétro-propagation. Arguments: dA {ndarray} -- Gradients de la loss par rapport aux sorties. Returns: ndarray -- Dérivée de la loss par rapport au input de la couche."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        N, channel, height, width = X.shape
        Pheight, Pwidth = self.pooling
        assert (height - Pheight) % self.stride[0] == 0
        assert (width - Pwidth) % self.stride[1] == 0
        out_height = np.uint32(1 + (height - Pheight) / self.stride[0])
        out_width = np.uint32(1 + (width - Pwidth) / self.stride[1])
        A = np.zeros((N, channel, out_height, out_width))
        indices = np.zeros((N, channel, out_height, out_width))
        for index in range(N):
            for c in range(channel):
                for i in range(0, height - Pheight + 1, self.stride[0]):
                    out_i = i // self.stride[0]
                    for j in range(0, width - Pwidth + 1, self.stride[1]):
                        max = -np.Inf
                        out_j = j // self.stride[1]
                        for ii in range(0, Pheight):
                            for jj in range(0, Pwidth):
                                if X[index, c, i + ii, j + jj] > max:
                                    max = X[index, c, i + ii, j + jj]
                                    indices[index, c, out_i, out_j] = ii * Pwidth + jj
                        A[index, c, out_i, out_j] = max
        self.cache = (X.shape, indices)
        return A
<|end_body_0|>

<|body_start_1|>
        X_shape, indices = self.cache
        N, channel, height, width = X_shape
        Pheight, Pwidth = self.pooling
        dX = np.zeros(X_shape)
        for index in range(N):
            for c in range(channel):
                for i in range(0, height - Pheight + 1, self.stride[0]):
                    out_i = i // self.stride[0]
                    for j in range(0, width - Pwidth + 1, self.stride[1]):
                        out_j = j // self.stride[1]
                        for ii in range(0, Pheight):
                            for jj in range(0, Pwidth):
                                if ii * Pwidth + jj == indices[index, c, out_i, out_j]:
                                    dX[index, c, i + ii, j + jj] += dA[index, c, out_i, out_j]
        return dX
<|end_body_1|>

Solution:
class MaxPool2DNaive:
    def forward_npdl(self, X, **kwargs):
        """Effectue la propagation avant d'une couche MaxPool2D Arguments: X {ndarray} -- Sortie de la couche précédente. Returns: ndarray -- Scores de la couche"""
        N, channel, height, width = X.shape
        Pheight, Pwidth = self.pooling
        assert (height - Pheight) % self.stride[0] == 0
        assert (width - Pwidth) % self.stride[1] == 0
        out_height = np.uint32(1 + (height - Pheight) / self.stride[0])
        out_width = np.uint32(1 + (width - Pwidth) / self.stride[1])
        A = np.zeros((N, channel, out_height, out_width))
        indices = np.zeros((N, channel, out_height, out_width))
        for index in range(N):
            for c in range(channel):
                for i in range(0, height - Pheight + 1, self.stride[0]):
                    out_i = i // self.stride[0]
                    for j in range(0, width - Pwidth + 1, self.stride[1]):
                        max = -np.Inf
                        out_j = j // self.stride[1]
                        for ii in range(0, Pheight):
                            for jj in range(0, Pwidth):
                                if X[index, c, i + ii, j + jj] > max:
                                    max = X[index, c, i + ii, j + jj]
                                    indices[index, c, out_i, out_j] = ii * Pwidth + jj
                        A[index, c, out_i, out_j] = max
        self.cache = (X.shape, indices)
        return A

    def backward_npdl(self, dA, **kwargs):
        """Effectue la rétro-propagation. Arguments: dA {ndarray} -- Gradients de la loss par rapport aux sorties. Returns: ndarray -- Dérivée de la loss par rapport au input de la couche."""
        X_shape, indices = self.cache
        N, channel, height, width = X_shape
        Pheight, Pwidth = self.pooling
        dX = np.zeros(X_shape)
        for index in range(N):
            for c in range(channel):
                for i in range(0, height - Pheight + 1, self.stride[0]):
                    out_i = i // self.stride[0]
                    for j in range(0, width - Pwidth + 1, self.stride[1]):
                        out_j = j // self.stride[1]
                        for ii in range(0, Pheight):
                            for jj in range(0, Pwidth):
                                if ii * Pwidth + jj == indices[index, c, out_i, out_j]:
                                    dX[index, c, i + ii, j + jj] += dA[index, c, out_i, out_j]
        return dX


estimateBatch

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

Class description:
Implement the DynamicRangeEstimator class.

Method signatures and docstrings:
- def estimate(self, imageWithFaceDetection: ImageWithFaceDetection, asyncEstimate: bool=False): Estimate dynamic range from single image Args: imageWithFaceDetection: image with face detection asyncEstimate: estimate or run estimation in background Returns: estimated dynamic range or async task if asyncEstimate is true Raises: LunaSDKException: if estimation is failed
- def estimateBatch(self, batch: ImageWithFaceDetection, asyncEstimate: bool=False): Estimate dynamic range from single image Args: batch: list of image with face detection or face detections asyncEstimate: estimate or run estimation in background Returns: list of estimated dynamic range or async task if asyncEstimate is true Raises: LunaSDKException: if estimation is failed

Implement the Python class `DynamicRangeEstimator` described below.

Class description:
Implement the DynamicRangeEstimator class.

Method signatures and docstrings:
- def estimate(self, imageWithFaceDetection: ImageWithFaceDetection, asyncEstimate: bool=False): Estimate dynamic range from single image Args: imageWithFaceDetection: image with face detection asyncEstimate: estimate or run estimation in background Returns: estimated dynamic range or async task if asyncEstimate is true Raises: LunaSDKException: if estimation is failed
- def estimateBatch(self, batch: ImageWithFaceDetection, asyncEstimate: bool=False): Estimate dynamic range from single image Args: batch: list of image with face detection or face detections asyncEstimate: estimate or run estimation in background Returns: list of estimated dynamic range or async task if asyncEstimate is true Raises: LunaSDKException: if estimation is failed

<|skeleton|>
class DynamicRangeEstimator:

    def estimate(self, imageWithFaceDetection: ImageWithFaceDetection, asyncEstimate: bool=False):
        """Estimate dynamic range from single image Args: imageWithFaceDetection: image with face detection asyncEstimate: estimate or run estimation in background Returns: estimated dynamic range or async task if asyncEstimate is true Raises: LunaSDKException: if estimation is failed"""
        <|body_0|>

    def estimateBatch(self, batch: ImageWithFaceDetection, asyncEstimate: bool=False):
        """Estimate dynamic range from single image Args: batch: list of image with face detection or face detections asyncEstimate: estimate or run estimation in background Returns: list of estimated dynamic range or async task if asyncEstimate is true Raises: LunaSDKException: if estimation is failed"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        if asyncEstimate:
            task = self._coreEstimator.asyncEstimate([imageWithFaceDetection.image.coreImage], [imageWithFaceDetection.boundingBox.coreEstimation])
            return AsyncTask(task, postProcessing)
        error, dynamicRangeEstimation = self._coreEstimator.estimate([imageWithFaceDetection.image.coreImage], [imageWithFaceDetection.boundingBox.coreEstimation])
        return postProcessing(error, dynamicRangeEstimation)
<|end_body_0|>

<|body_start_1|>
        coreImages = [row.image.coreImage for row in batch]
        detections = [row.boundingBox.coreEstimation for row in batch]
        validateInputByBatchEstimator(self._coreEstimator, coreImages, detections)
        if asyncEstimate:
            task = self._coreEstimator.asyncEstimate(coreImages, detections)
            return AsyncTask(task, postProcessingBatch)
        error, coreDynamicRangeList = self._coreEstimator.estimate(coreImages, detections)
        return postProcessingBatch(error, coreDynamicRangeList)
<|end_body_1|>

Solution:
class DynamicRangeEstimator:
    def estimate(self, imageWithFaceDetection: ImageWithFaceDetection, asyncEstimate: bool=False):
        """Estimate dynamic range from single image Args: imageWithFaceDetection: image with face detection asyncEstimate: estimate or run estimation in background Returns: estimated dynamic range or async task if asyncEstimate is true Raises: LunaSDKException: if estimation is failed"""
        if asyncEstimate:
            task = self._coreEstimator.asyncEstimate([imageWithFaceDetection.image.coreImage], [imageWithFaceDetection.boundingBox.coreEstimation])
            return AsyncTask(task, postProcessing)
        error, dynamicRangeEstimation = self._coreEstimator.estimate([imageWithFaceDetection.image.coreImage], [imageWithFaceDetection.boundingBox.coreEstimation])
        return postProcessing(error, dynamicRangeEstimation)

    def estimateBatch(self, batch: ImageWithFaceDetection, asyncEstimate: bool=False):
        """Estimate dynamic range from single image Args: batch: list of image with face detection or face detections asyncEstimate: estimate or run estimation in background Returns: list of estimated dynamic range or async task if asyncEstimate is true Raises: LunaSDKException: if estimation is failed"""
        coreImages = [row.image.coreImage for row in batch]
        detections = [row.boundingBox.coreEstimation for row in batch]
        validateInputByBatchEstimator(self._coreEstimator, coreImages, detections)
        if asyncEstimate:
            task = self._coreEstimator.asyncEstimate(coreImages, detections)
            return AsyncTask(task, postProcessingBatch)
        error, coreDynamicRangeList = self._coreEstimator.estimate(coreImages, detections)
        return postProcessingBatch(error, coreDynamicRangeList)


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

Class description:
Find a maximal independent set.

Method signatures and docstrings:
- def __init__(self, graph): The algorithm initialization.
- def run(self, source=None): Executable pseudocode.

Implement the Python class `SmallestFirstIndependentSet3` described below.

Class description:
Find a maximal independent set.

Method signatures and docstrings:
- def __init__(self, graph): The algorithm initialization.
- def run(self, source=None): Executable pseudocode.

<|skeleton|>
class SmallestFirstIndependentSet3:
    """Find a maximal independent set."""

    def __init__(self, graph):
        """The algorithm initialization."""
        <|body_0|>

    def run(self, source=None):
        """Executable pseudocode."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        if graph.is_directed():
            raise ValueError('the graph is directed')
        self.graph = graph
        for edge in self.graph.iteredges():
            if edge.source == edge.target:
                raise ValueError('a loop detected')
        self.independent_set = dict(((node, False) for node in self.graph.iternodes()))
        self.cardinality = 0
        self.source = None
<|end_body_0|>

<|body_start_1|>
        used = dict(((node, False) for node in self.graph.iternodes()))
        if source is not None:
            self.source = source
            self.independent_set[source] = True
            used[source] = True
            self.cardinality += 1
            for target in self.graph.iteradjacent(source):
                used[target] = True
        for source in sorted(self.graph.iternodes(), key=self.graph.degree):
            if used[source]:
                continue
            self.independent_set[source] = True
            used[source] = True
            self.cardinality += 1
            for target in self.graph.iteradjacent(source):
                used[target] = True
<|end_body_1|>

Solution:
class SmallestFirstIndependentSet3:
    """Find a maximal independent set."""

    def __init__(self, graph):
        """The algorithm initialization."""
        if graph.is_directed():
            raise ValueError('the graph is directed')
        self.graph = graph
        for edge in self.graph.iteredges():
            if edge.source == edge.target:
                raise ValueError('a loop detected')
        self.independent_set = dict(((node, False) for node in self.graph.iternodes()))
        self.cardinality = 0
        self.source = None

    def run(self, source=None):
        """Executable pseudocode."""
        used = dict(((node, False) for node in self.graph.iternodes()))
        if source is not None:
            self.source = source
            self.independent_set[source] = True
            used[source] = True
            self.cardinality += 1
            for target in self.graph.iteradjacent(source):
                used[target] = True
        for source in sorted(self.graph.iternodes(), key=self.graph.degree):
            if used[source]:
                continue
            self.independent_set[source] = True
            used[source] = True
            self.cardinality += 1
            for target in self.graph.iteradjacent(source):
                used[target] = True


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

Class description:
Implement the ProtocolWrapper class.

Method signatures and docstrings:
- def __init__(self, env, protocol): :param env: :param protocol:
- def step(self, action): :param action: :return:
- def reset(self): :return:

Implement the Python class `ProtocolWrapper` described below.

Class description:
Implement the ProtocolWrapper class.

Method signatures and docstrings:
- def __init__(self, env, protocol): :param env: :param protocol:
- def step(self, action): :param action: :return:
- def reset(self): :return:

<|skeleton|>
class ProtocolWrapper:

    def __init__(self, env, protocol):
        """:param env: :param protocol:"""
        <|body_0|>

    def step(self, action):
        """:param action: :return:"""
        <|body_1|>

    def reset(self):
        """:return:"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        super(ProtocolWrapper, self).__init__(env)
        self.protocol = protocol
        self.env.add_wrapper_info({'evaluation_environment': self.protocol.get_name()})
        self._elapsed_episodes = 0
        self._elapsed_timesteps = 0
        return
<|end_body_0|>

<|body_start_1|>
        observation, reward, done, info = self.env.step(action)
        self._elapsed_timesteps += 1
        invalid_interventions = 0
        interventions_dict = self.protocol.get_intervention(episode=self._elapsed_episodes, timestep=self._elapsed_episodes)
        if interventions_dict is not None:
            success_signal, observation = self.env.do_intervention(interventions_dict=interventions_dict)
            while not success_signal and invalid_interventions < 5:
                invalid_interventions += 1
                interventions_dict = self.protocol.get_intervention(episode=self._elapsed_episodes, timestep=self._elapsed_episodes)
                if interventions_dict is not None:
                    success_signal, observation = self.env.do_intervention(interventions_dict=interventions_dict)
                else:
                    break
        return (observation, reward, done, info)
<|end_body_1|>

<|body_start_2|>
        self._elapsed_episodes += 1
        self._elapsed_timesteps = 0
        invalid_interventions = 0
        observation = self.env.reset()
        interventions_dict = self.protocol.get_intervention(episode=self._elapsed_episodes, timestep=0)
        if interventions_dict is not None:
            success_signal, observation = self.env.do_intervention(interventions_dict)
            while not success_signal and invalid_interventions < 5:
                invalid_interventions += 1
                interventions_dict = self.protocol.get_intervention(episode=self._elapsed_episodes, timestep=0)
                if interventions_dict is not None:
                    success_signal, observation = self.env.do_intervention(interventions_dict)
                else:
                    break
        return observation
<|end_body_2|>

Solution:
class ProtocolWrapper:
    def __init__(self, env, protocol):
        """:param env: :param protocol:"""
        super(ProtocolWrapper, self).__init__(env)
        self.protocol = protocol
        self.env.add_wrapper_info({'evaluation_environment': self.protocol.get_name()})
        self._elapsed_episodes = 0
        self._elapsed_timesteps = 0
        return

    def step(self, action):
        """:param action: :return:"""
        observation, reward, done, info = self.env.step(action)
        self._elapsed_timesteps += 1
        invalid_interventions = 0
        interventions_dict = self.protocol.get_intervention(episode=self._elapsed_episodes, timestep=self._elapsed_episodes)
        if interventions_dict is not None:
            success_signal, observation = self.env.do_intervention(interventions_dict=interventions_dict)
            while not success_signal and invalid_interventions < 5:
                invalid_interventions += 1
                interventions_dict = self.protocol.get_intervention(episode=self._elapsed_episodes, timestep=self._elapsed_episodes)
                if interventions_dict is not None:
                    success_signal, observation = self.env.do_intervention(interventions_dict=interventions_dict)
                else:
                    break
        return (observation, reward, done, info)

    def reset(self):
        """:return:"""
        self._elapsed_episodes += 1
        self._elapsed_timesteps = 0
        invalid_interventions = 0
        observation = self.env.reset()
        interventions_dict = self.protocol.get_intervention(episode=self._elapsed_episodes, timestep=0)
        if interventions_dict is not None:
            success_signal, observation = self.env.do_intervention(interventions_dict)
            while not success_signal and invalid_interventions < 5:
                invalid_interventions += 1
                interventions_dict = self.protocol.get_intervention(episode=self._elapsed_episodes, timestep=0)
                if interventions_dict is not None:
                    success_signal, observation = self.env.do_intervention(interventions_dict)
                else:
                    break
        return observation


StreamingRecognize

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

Class description:
Implement the VisionServicer class.

Method signatures and docstrings:
- def Recognize(self, request, context): sync call for result, use by service-app usually
- def StreamingRecognize(self, request_iterator, context): sync call , use by rcu or other end point receive multi-face or other

Implement the Python class `VisionServicer` described below.

Class description:
Implement the VisionServicer class.

Method signatures and docstrings:
- def Recognize(self, request, context): sync call for result, use by service-app usually
- def StreamingRecognize(self, request_iterator, context): sync call , use by rcu or other end point receive multi-face or other

<|skeleton|>
class VisionServicer:

    def Recognize(self, request, context):
        """sync call for result, use by service-app usually"""
        <|body_0|>

    def StreamingRecognize(self, request_iterator, context):
        """sync call , use by rcu or other end point receive multi-face or other"""
        <|body_1|>

<|end_skeleton|>

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

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

Solution:
class VisionServicer:
    def Recognize(self, request, context):
        """sync call for result, use by service-app usually"""
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details('Method not implemented!')
        raise NotImplementedError('Method not implemented!')

    def StreamingRecognize(self, request_iterator, context):
        """sync call , use by rcu or other end point receive multi-face or other"""
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details('Method not implemented!')
        raise NotImplementedError('Method not implemented!')


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

Class description:
Function to implement two stacks in a array. Two stacks will start from index 0 and index n-1 and keep pushing the new elements in the middle of the array until their is not space left between the top of stack1 and stack2. Index of top of two stacks will be saved using two variables top1 and top2.

Method signatures and docstrings:
- def __init__(self, n): array of size n to store elements of the stack. top1 and top2 to store indexes of the top of the stack.
- def push1(self, x): Function to push element in the stack. It checks the difference between indexes of the two tops to check for stack full. If not, it increments the stack top index and pushed the element in the array. :param x: Int :return: None
- def push2(self, x): Function to push element in the stack. It checks the difference between indexes of the two tops to check for stack full. If not, it increments the stack top index and pushed the element in the array. :param x: int :return: None
- def pop1(self): Function to pop the element from the stack. It check the stack index to check for empty stack. It not, it removes the element at the stack top and decrement the index of stack top :return: Int
- def pop2(self): Function to pop the element from the stack. It check the stack index to check for empty stack. It not, it removes the element at the stack top and decrement the index of stack top :return: Int

Implement the Python class `TwoStacks` described below.

Class description:
Function to implement two stacks in a array. Two stacks will start from index 0 and index n-1 and keep pushing the new elements in the middle of the array until their is not space left between the top of stack1 and stack2. Index of top of two stacks will be saved using two variables top1 and top2.

Method signatures and docstrings:
- def __init__(self, n): array of size n to store elements of the stack. top1 and top2 to store indexes of the top of the stack.
- def push1(self, x): Function to push element in the stack. It checks the difference between indexes of the two tops to check for stack full. If not, it increments the stack top index and pushed the element in the array. :param x: Int :return: None
- def push2(self, x): Function to push element in the stack. It checks the difference between indexes of the two tops to check for stack full. If not, it increments the stack top index and pushed the element in the array. :param x: int :return: None
- def pop1(self): Function to pop the element from the stack. It check the stack index to check for empty stack. It not, it removes the element at the stack top and decrement the index of stack top :return: Int
- def pop2(self): Function to pop the element from the stack. It check the stack index to check for empty stack. It not, it removes the element at the stack top and decrement the index of stack top :return: Int

<|skeleton|>
class TwoStacks:
    """Function to implement two stacks in a array. Two stacks will start from index 0 and index n-1 and keep pushing the new elements in the middle of the array until their is not space left between the top of stack1 and stack2. Index of top of two stacks will be saved using two variables top1 and top2."""

    def __init__(self, n):
        """array of size n to store elements of the stack. top1 and top2 to store indexes of the top of the stack."""
        <|body_0|>

    def push1(self, x):
        """Function to push element in the stack. It checks the difference between indexes of the two tops to check for stack full. If not, it increments the stack top index and pushed the element in the array. :param x: Int :return: None"""
        <|body_1|>

    def push2(self, x):
        """Function to push element in the stack. It checks the difference between indexes of the two tops to check for stack full. If not, it increments the stack top index and pushed the element in the array. :param x: int :return: None"""
        <|body_2|>

    def pop1(self):
        """Function to pop the element from the stack. It check the stack index to check for empty stack. It not, it removes the element at the stack top and decrement the index of stack top :return: Int"""
        <|body_3|>

    def pop2(self):
        """Function to pop the element from the stack. It check the stack index to check for empty stack. It not, it removes the element at the stack top and decrement the index of stack top :return: Int"""
        <|body_4|>

<|end_skeleton|>

<|body_start_0|>
        self.array = [None] * n
        self.top1 = -1
        self.top2 = len(self.array)
<|end_body_0|>

<|body_start_1|>
        if self.top2 - 1 == self.top1:
            print('Memory out of bound')
        else:
            self.top1 += 1
            self.array[self.top1] = x
<|end_body_1|>

<|body_start_2|>
        if self.top2 - 1 == self.top1:
            print('Memory out of bound')
        else:
            self.top2 -= 1
            self.array[self.top2] = x
<|end_body_2|>

<|body_start_3|>
        if self.top1 >= 0:
            x = self.array[self.top1]
            self.array[self.top1] = None
            self.top1 -= 1
            return x
        else:
            print('Stack underflow')
<|end_body_3|>

<|body_start_4|>
        if self.top2 <= len(self.array) - 1:
            x = self.array[self.top2]
            self.array[self.top2] = None
            self.top2 += 1
            return x
        else:
            print('Stack underflow')
<|end_body_4|>

Solution:
class TwoStacks:
    """Function to implement two stacks in a array. Two stacks will start from index 0 and index n-1 and keep pushing the new elements in the middle of the array until their is not space left between the top of stack1 and stack2. Index of top of two stacks will be saved using two variables top1 and top2."""

    def __init__(self, n):
        """array of size n to store elements of the stack. top1 and top2 to store indexes of the top of the stack."""
        self.array = [None] * n
        self.top1 = -1
        self.top2 = len(self.array)

    def push1(self, x):
        """Function to push element in the stack. It checks the difference between indexes of the two tops to check for stack full. If not, it increments the stack top index and pushed the element in the array. :param x: Int :return: None"""
        if self.top2 - 1 == self.top1:
            print('Memory out of bound')
        else:
            self.top1 += 1
            self.array[self.top1] = x

    def push2(self, x):
        """Function to push element in the stack. It checks the difference between indexes of the two tops to check for stack full. If not, it increments the stack top index and pushed the element in the array. :param x: int :return: None"""
        if self.top2 - 1 == self.top1:
            print('Memory out of bound')
        else:
            self.top2 -= 1
            self.array[self.top2] = x

    def pop1(self):
        """Function to pop the element from the stack. It check the stack index to check for empty stack. It not, it removes the element at the stack top and decrement the index of stack top :return: Int"""
        if self.top1 >= 0:
            x = self.array[self.top1]
            self.array[self.top1] = None
            self.top1 -= 1
            return x
        else:
            print('Stack underflow')

    def pop2(self):
        """Function to pop the element from the stack. It check the stack index to check for empty stack. It not, it removes the element at the stack top and decrement the index of stack top :return: Int"""
        if self.top2 <= len(self.array) - 1:
            x = self.array[self.top2]
            self.array[self.top2] = None
            self.top2 += 1
            return x
        else:
            print('Stack underflow')


click

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

Class description:
Implement the ClickInterface class.

Method signatures and docstrings:
- def click(self, handler: Handler, options: Optional[Dict[str, Any]]=None) -> str: Add click event listener setting. Parameters ---------- handler : Handler Callable that called when this instance is clicked. options : dict or None, default None Optional arguments dictionary to be passed to handler. Returns ------- name : str Handler's name.
- def _initialize_click_handlers_if_not_initialized(self) -> None: Initialize _click_handlers attribute if it is not initialized yet.
- def unbind_click(self, handler: Handler) -> None: Unbind specified handler's click event. Parameters ---------- handler : Handler Callable to be unbinded.
- def unbind_click_all(self) -> None: Unbind all click events.

Implement the Python class `ClickInterface` described below.

Class description:
Implement the ClickInterface class.

Method signatures and docstrings:
- def click(self, handler: Handler, options: Optional[Dict[str, Any]]=None) -> str: Add click event listener setting. Parameters ---------- handler : Handler Callable that called when this instance is clicked. options : dict or None, default None Optional arguments dictionary to be passed to handler. Returns ------- name : str Handler's name.
- def _initialize_click_handlers_if_not_initialized(self) -> None: Initialize _click_handlers attribute if it is not initialized yet.
- def unbind_click(self, handler: Handler) -> None: Unbind specified handler's click event. Parameters ---------- handler : Handler Callable to be unbinded.
- def unbind_click_all(self) -> None: Unbind all click events.

<|skeleton|>
class ClickInterface:

    def click(self, handler: Handler, options: Optional[Dict[str, Any]]=None) -> str:
        """Add click event listener setting. Parameters ---------- handler : Handler Callable that called when this instance is clicked. options : dict or None, default None Optional arguments dictionary to be passed to handler. Returns ------- name : str Handler's name."""
        <|body_0|>

    def _initialize_click_handlers_if_not_initialized(self) -> None:
        """Initialize _click_handlers attribute if it is not initialized yet."""
        <|body_1|>

    def unbind_click(self, handler: Handler) -> None:
        """Unbind specified handler's click event. Parameters ---------- handler : Handler Callable to be unbinded."""
        <|body_2|>

    def unbind_click_all(self) -> None:
        """Unbind all click events."""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        from apysc import EventType
        from apysc import MouseEvent
        from apysc.event.handler import append_handler_expression
        from apysc.event.handler import get_handler_name
        from apysc.type.variable_name_interface import VariableNameInterface
        self_instance: VariableNameInterface = self._validate_self_is_variable_name_interface()
        self._initialize_click_handlers_if_not_initialized()
        name: str = get_handler_name(handler=handler, instance=self)
        self._set_handler_data(handler=handler, handlers_dict=self._click_handlers, options=options)
        self._append_event_binding_expression(name=name, event_type=EventType.CLICK)
        e: MouseEvent = MouseEvent(this=self_instance)
        append_handler_expression(handler_data=self._click_handlers[name], handler_name=name, e=e)
        return name
<|end_body_0|>

<|body_start_1|>
        if hasattr(self, '_click_handlers'):
            return
        self._click_handlers = {}
<|end_body_1|>

<|body_start_2|>
        from apysc import EventType
        self._initialize_click_handlers_if_not_initialized()
        self._unbind_event(handler=handler, event_type=EventType.CLICK, handlers_dict=self._click_handlers)
<|end_body_2|>

<|body_start_3|>
        from apysc import EventType
        self._initialize_click_handlers_if_not_initialized()
        self._unbind_all_events(event_type=EventType.CLICK, handlers_dict=self._click_handlers)
<|end_body_3|>

Solution:
class ClickInterface:
    def click(self, handler: Handler, options: Optional[Dict[str, Any]]=None) -> str:
        """Add click event listener setting. Parameters ---------- handler : Handler Callable that called when this instance is clicked. options : dict or None, default None Optional arguments dictionary to be passed to handler. Returns ------- name : str Handler's name."""
        from apysc import EventType
        from apysc import MouseEvent
        from apysc.event.handler import append_handler_expression
        from apysc.event.handler import get_handler_name
        from apysc.type.variable_name_interface import VariableNameInterface
        self_instance: VariableNameInterface = self._validate_self_is_variable_name_interface()
        self._initialize_click_handlers_if_not_initialized()
        name: str = get_handler_name(handler=handler, instance=self)
        self._set_handler_data(handler=handler, handlers_dict=self._click_handlers, options=options)
        self._append_event_binding_expression(name=name, event_type=EventType.CLICK)
        e: MouseEvent = MouseEvent(this=self_instance)
        append_handler_expression(handler_data=self._click_handlers[name], handler_name=name, e=e)
        return name

    def _initialize_click_handlers_if_not_initialized(self) -> None:
        """Initialize _click_handlers attribute if it is not initialized yet."""
        if hasattr(self, '_click_handlers'):
            return
        self._click_handlers = {}

    def unbind_click(self, handler: Handler) -> None:
        """Unbind specified handler's click event. Parameters ---------- handler : Handler Callable to be unbinded."""
        from apysc import EventType
        self._initialize_click_handlers_if_not_initialized()
        self._unbind_event(handler=handler, event_type=EventType.CLICK, handlers_dict=self._click_handlers)

    def unbind_click_all(self) -> None:
        """Unbind all click events."""
        from apysc import EventType
        self._initialize_click_handlers_if_not_initialized()
        self._unbind_all_events(event_type=EventType.CLICK, handlers_dict=self._click_handlers)


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

Class description:
Callback class for handling telegram received callbacks.

Method signatures and docstrings:
- def __init__(self, callback: AsyncTelegramCallback, address_filters: list[AddressFilter] | None=None, group_addresses: list[GroupAddress | InternalGroupAddress] | None=None, match_for_outgoing_telegrams: bool=False): Initialize Callback class.
- def is_within_filter(self, telegram: Telegram) -> bool: Test if callback is filtering for group address.

Implement the Python class `Callback` described below.

Class description:
Callback class for handling telegram received callbacks.

Method signatures and docstrings:
- def __init__(self, callback: AsyncTelegramCallback, address_filters: list[AddressFilter] | None=None, group_addresses: list[GroupAddress | InternalGroupAddress] | None=None, match_for_outgoing_telegrams: bool=False): Initialize Callback class.
- def is_within_filter(self, telegram: Telegram) -> bool: Test if callback is filtering for group address.

<|skeleton|>
class Callback:
    """Callback class for handling telegram received callbacks."""

    def __init__(self, callback: AsyncTelegramCallback, address_filters: list[AddressFilter] | None=None, group_addresses: list[GroupAddress | InternalGroupAddress] | None=None, match_for_outgoing_telegrams: bool=False):
        """Initialize Callback class."""
        <|body_0|>

    def is_within_filter(self, telegram: Telegram) -> bool:
        """Test if callback is filtering for group address."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.callback = callback
        self._match_all = address_filters is None and group_addresses is None
        self._match_outgoing = match_for_outgoing_telegrams
        self.address_filters = [] if address_filters is None else address_filters
        self.group_addresses = [] if group_addresses is None else group_addresses
<|end_body_0|>

<|body_start_1|>
        if not self._match_outgoing and telegram.direction == TelegramDirection.OUTGOING:
            return False
        if self._match_all:
            return True
        if isinstance(telegram.destination_address, (GroupAddress, InternalGroupAddress)):
            for address_filter in self.address_filters:
                if address_filter.match(telegram.destination_address):
                    return True
            for group_address in self.group_addresses:
                if telegram.destination_address == group_address:
                    return True
        return False
<|end_body_1|>

Solution:
class Callback:
    """Callback class for handling telegram received callbacks."""

    def __init__(self, callback: AsyncTelegramCallback, address_filters: list[AddressFilter] | None=None, group_addresses: list[GroupAddress | InternalGroupAddress] | None=None, match_for_outgoing_telegrams: bool=False):
        """Initialize Callback class."""
        self.callback = callback
        self._match_all = address_filters is None and group_addresses is None
        self._match_outgoing = match_for_outgoing_telegrams
        self.address_filters = [] if address_filters is None else address_filters
        self.group_addresses = [] if group_addresses is None else group_addresses

    def is_within_filter(self, telegram: Telegram) -> bool:
        """Test if callback is filtering for group address."""
        if not self._match_outgoing and telegram.direction == TelegramDirection.OUTGOING:
            return False
        if self._match_all:
            return True
        if isinstance(telegram.destination_address, (GroupAddress, InternalGroupAddress)):
            for address_filter in self.address_filters:
                if address_filter.match(telegram.destination_address):
                    return True
            for group_address in self.group_addresses:
                if telegram.destination_address == group_address:
                    return True
        return False


validate

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

Class description:
Type for evaluating instances of Python classes.

Method signatures and docstrings:
- def validate(cls, obj, raise_errors=False): Validate an object to check if it could be of this type. Args: obj (object): Object to validate. raise_errors (bool, optional): If True, errors will be raised when the object fails to be validated. Defaults to False. Returns: bool: True if the object could be of this type, False otherwise.
- def encode_data(cls, obj, typedef): Encode an object's data. Args: obj (object): Object to encode. typedef (dict): Type definition that should be used to encode the object. Returns: string: Encoded object.
- def decode_data(cls, obj, typedef): Decode an object. Args: obj (string): Encoded object to decode. typedef (dict): Type definition that should be used to decode the object. Returns: object: Decoded object.
- def _generate_data(cls, typedef): Generate mock data for the specified type. Args: typedef (dict): Type definition. Returns: object: Python object of the specified type.

Implement the Python class `InstanceMetaschemaType` described below.

Class description:
Type for evaluating instances of Python classes.

Method signatures and docstrings:
- def validate(cls, obj, raise_errors=False): Validate an object to check if it could be of this type. Args: obj (object): Object to validate. raise_errors (bool, optional): If True, errors will be raised when the object fails to be validated. Defaults to False. Returns: bool: True if the object could be of this type, False otherwise.
- def encode_data(cls, obj, typedef): Encode an object's data. Args: obj (object): Object to encode. typedef (dict): Type definition that should be used to encode the object. Returns: string: Encoded object.
- def decode_data(cls, obj, typedef): Decode an object. Args: obj (string): Encoded object to decode. typedef (dict): Type definition that should be used to decode the object. Returns: object: Decoded object.
- def _generate_data(cls, typedef): Generate mock data for the specified type. Args: typedef (dict): Type definition. Returns: object: Python object of the specified type.

<|skeleton|>
class InstanceMetaschemaType:
    """Type for evaluating instances of Python classes."""

    def validate(cls, obj, raise_errors=False):
        """Validate an object to check if it could be of this type. Args: obj (object): Object to validate. raise_errors (bool, optional): If True, errors will be raised when the object fails to be validated. Defaults to False. Returns: bool: True if the object could be of this type, False otherwise."""
        <|body_0|>

    def encode_data(cls, obj, typedef):
        """Encode an object's data. Args: obj (object): Object to encode. typedef (dict): Type definition that should be used to encode the object. Returns: string: Encoded object."""
        <|body_1|>

    def decode_data(cls, obj, typedef):
        """Decode an object. Args: obj (string): Encoded object to decode. typedef (dict): Type definition that should be used to decode the object. Returns: object: Decoded object."""
        <|body_2|>

    def _generate_data(cls, typedef):
        """Generate mock data for the specified type. Args: typedef (dict): Type definition. Returns: object: Python object of the specified type."""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        try:
            ArgsMetaschemaProperty.instance2args(obj)
            KwargsMetaschemaProperty.instance2kwargs(obj)
            return True
        except MetaschemaTypeError:
            if raise_errors:
                raise ValueError("Class dosn't have an input_args attribute.")
            return False
<|end_body_0|>

<|body_start_1|>
        args = ArgsMetaschemaProperty.instance2args(obj)
        kwargs = KwargsMetaschemaProperty.instance2kwargs(obj)
        typedef_args = None
        typedef_kwargs = None
        if isinstance(typedef, dict):
            if 'args' in typedef:
                typedef_args = {'items': typedef['args']}
            if 'kwargs' in typedef:
                typedef_kwargs = {'properties': typedef['kwargs']}
        out = [JSONArrayMetaschemaType.encode_data(args, typedef_args), JSONObjectMetaschemaType.encode_data(kwargs, typedef_kwargs)]
        return out
<|end_body_1|>

<|body_start_2|>
        typedef = cls.normalize_definition(typedef)
        assert isinstance(obj, list)
        assert len(obj) == 2
        args = JSONArrayMetaschemaType.decode_data(obj[0], {'items': typedef.get('args', [])})
        kwargs = JSONObjectMetaschemaType.decode_data(obj[1], {'properties': typedef.get('kwargs', {})})
        return typedef['class'](*args, **kwargs)
<|end_body_2|>

<|body_start_3|>
        typedef = cls.normalize_definition(typedef)
        args = JSONArrayMetaschemaType.generate_data({'type': 'array', 'items': typedef.get('args', [])})
        kwargs = JSONObjectMetaschemaType.generate_data({'type': 'object', 'properties': typedef.get('kwargs', {})})
        return typedef['class'](*args, **kwargs)
<|end_body_3|>

Solution:
class InstanceMetaschemaType:
    """Type for evaluating instances of Python classes."""

    def validate(cls, obj, raise_errors=False):
        """Validate an object to check if it could be of this type. Args: obj (object): Object to validate. raise_errors (bool, optional): If True, errors will be raised when the object fails to be validated. Defaults to False. Returns: bool: True if the object could be of this type, False otherwise."""
        try:
            ArgsMetaschemaProperty.instance2args(obj)
            KwargsMetaschemaProperty.instance2kwargs(obj)
            return True
        except MetaschemaTypeError:
            if raise_errors:
                raise ValueError("Class dosn't have an input_args attribute.")
            return False

    def encode_data(cls, obj, typedef):
        """Encode an object's data. Args: obj (object): Object to encode. typedef (dict): Type definition that should be used to encode the object. Returns: string: Encoded object."""
        args = ArgsMetaschemaProperty.instance2args(obj)
        kwargs = KwargsMetaschemaProperty.instance2kwargs(obj)
        typedef_args = None
        typedef_kwargs = None
        if isinstance(typedef, dict):
            if 'args' in typedef:
                typedef_args = {'items': typedef['args']}
            if 'kwargs' in typedef:
                typedef_kwargs = {'properties': typedef['kwargs']}
        out = [JSONArrayMetaschemaType.encode_data(args, typedef_args), JSONObjectMetaschemaType.encode_data(kwargs, typedef_kwargs)]
        return out

    def decode_data(cls, obj, typedef):
        """Decode an object. Args: obj (string): Encoded object to decode. typedef (dict): Type definition that should be used to decode the object. Returns: object: Decoded object."""
        typedef = cls.normalize_definition(typedef)
        assert isinstance(obj, list)
        assert len(obj) == 2
        args = JSONArrayMetaschemaType.decode_data(obj[0], {'items': typedef.get('args', [])})
        kwargs = JSONObjectMetaschemaType.decode_data(obj[1], {'properties': typedef.get('kwargs', {})})
        return typedef['class'](*args, **kwargs)

    def _generate_data(cls, typedef):
        """Generate mock data for the specified type. Args: typedef (dict): Type definition. Returns: object: Python object of the specified type."""
        typedef = cls.normalize_definition(typedef)
        args = JSONArrayMetaschemaType.generate_data({'type': 'array', 'items': typedef.get('args', [])})
        kwargs = JSONObjectMetaschemaType.generate_data({'type': 'object', 'properties': typedef.get('kwargs', {})})
        return typedef['class'](*args, **kwargs)