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

Class description:
Implement the MovingAverage class.

Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float

Implement the Python class `MovingAverage` described below.

Class description:
Implement the MovingAverage class.

Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float

<|skeleton|>
class MovingAverage:

    def __init__(self, size):
        """Initialize your data structure here. :type size: int"""
        <|body_0|>

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

<|end_skeleton|>

<|body_start_0|>
        self.array = [None for _ in range(size)]
        self.i = 0
        self.total = 0
<|end_body_0|>

<|body_start_1|>
        if self.array[self.i] is not None:
            self.total -= self.array[self.i]
        self.total += val
        self.array[self.i] = val
        self.i = (self.i + 1) % len(self.array)
        count = len(self.array)
        if self.array[-1] is None:
            count = self.i
        return self.total / float(count)
<|end_body_1|>

Solution:
class MovingAverage:
    def __init__(self, size):
        """Initialize your data structure here. :type size: int"""
        self.array = [None for _ in range(size)]
        self.i = 0
        self.total = 0

    def next(self, val):
        """:type val: int :rtype: float"""
        if self.array[self.i] is not None:
            self.total -= self.array[self.i]
        self.total += val
        self.array[self.i] = val
        self.i = (self.i + 1) % len(self.array)
        count = len(self.array)
        if self.array[-1] is None:
            count = self.i
        return self.total / float(count)


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

Class description:
Implement the RevisionPermissionMixin class.

Method signatures and docstrings:
- def test_func(self): Check if trial period is over and if user is allowed to access requested object.
- def handle_no_permission(self): Ask user to login or to subscribe to a cards plan.

Implement the Python class `RevisionPermissionMixin` described below.

Class description:
Implement the RevisionPermissionMixin class.

Method signatures and docstrings:
- def test_func(self): Check if trial period is over and if user is allowed to access requested object.
- def handle_no_permission(self): Ask user to login or to subscribe to a cards plan.

<|skeleton|>
class RevisionPermissionMixin:

    def test_func(self):
        """Check if trial period is over and if user is allowed to access requested object."""
        <|body_0|>

    def handle_no_permission(self):
        """Ask user to login or to subscribe to a cards plan."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        if self.request.user.is_authenticated and self.request.user.deck.count() > 50:
            try:
                return self.request.user.has_active_subscription or self.request.user.subscription.type.product.attr.access_cards
            except:
                return False
        if not hasattr(self, 'get_object'):
            if self.request.user.is_authenticated:
                return True
            else:
                return False
        self.object = self.get_object()
        if isinstance(self.object, Card):
            card = self.object
        else:
            card = self.object.card
        if not self.request.user.is_authenticated:
            return card.public
        else:
            return Card.objects.for_user(self.request.user).filter(id=card.id).exists() or self.request.user.deck.filter(card=card).exists()
<|end_body_0|>

<|body_start_1|>
        if not self.request.user.is_authenticated:
            return BBLoginRequiredMixin.handle_no_permission(self)
        try:
            if not self.student.subscription.type.product.attr.access_cards:
                return redirect(reverse('cards:stop', kwargs={'id': 'trialover'}))
        except:
            return redirect(reverse('cards:stop', kwargs={'id': 'trialover'}))
        raise PermissionDenied
<|end_body_1|>

Solution:
class RevisionPermissionMixin:
    def test_func(self):
        """Check if trial period is over and if user is allowed to access requested object."""
        if self.request.user.is_authenticated and self.request.user.deck.count() > 50:
            try:
                return self.request.user.has_active_subscription or self.request.user.subscription.type.product.attr.access_cards
            except:
                return False
        if not hasattr(self, 'get_object'):
            if self.request.user.is_authenticated:
                return True
            else:
                return False
        self.object = self.get_object()
        if isinstance(self.object, Card):
            card = self.object
        else:
            card = self.object.card
        if not self.request.user.is_authenticated:
            return card.public
        else:
            return Card.objects.for_user(self.request.user).filter(id=card.id).exists() or self.request.user.deck.filter(card=card).exists()

    def handle_no_permission(self):
        """Ask user to login or to subscribe to a cards plan."""
        if not self.request.user.is_authenticated:
            return BBLoginRequiredMixin.handle_no_permission(self)
        try:
            if not self.student.subscription.type.product.attr.access_cards:
                return redirect(reverse('cards:stop', kwargs={'id': 'trialover'}))
        except:
            return redirect(reverse('cards:stop', kwargs={'id': 'trialover'}))
        raise PermissionDenied


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

Class description:
Maps \\Device\\HarddiskVolumeN to N: on Windows.

Method signatures and docstrings:
- def __init__(self): Lazy loads the cache.
- def to_win32(self, path): Converts a native NT path to Win32/DOS compatible path.

Implement the Python class `DosDriveMap` described below.

Class description:
Maps \\Device\\HarddiskVolumeN to N: on Windows.

Method signatures and docstrings:
- def __init__(self): Lazy loads the cache.
- def to_win32(self, path): Converts a native NT path to Win32/DOS compatible path.

<|skeleton|>
class DosDriveMap:
    """Maps \\Device\\HarddiskVolumeN to N: on Windows."""

    def __init__(self):
        """Lazy loads the cache."""
        <|body_0|>

    def to_win32(self, path):
        """Converts a native NT path to Win32/DOS compatible path."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        if not self._MAPPING:
            self._MAPPING['\\Device\\Mup'] = None
            self._MAPPING['\\SystemRoot'] = os.environ['SystemRoot']
            for letter in (chr(l) for l in range(ord('C'), ord('Z') + 1)):
                try:
                    letter = '%s:' % letter
                    mapped = QueryDosDevice(letter)
                    if mapped in self._MAPPING:
                        logging.warning("Two drives: '%s' and '%s', are mapped to the same disk. Drive letters are a user-mode concept and the kernel traces only have NT path, so all accesses will be associated with the first drive letter, independent of the actual letter used by the code" % (self._MAPPING[mapped], letter))
                    else:
                        self._MAPPING[mapped] = letter
                except WindowsError:
                    pass
<|end_body_0|>

<|body_start_1|>
        match = re.match('(^\\\\Device\\\\[a-zA-Z0-9]+)(\\\\.*)?$', path)
        if not match:
            raise ValueError("Can't convert %s into a Win32 compatible path" % path, path)
        if not match.group(1) in self._MAPPING:
            return None
        drive = self._MAPPING[match.group(1)]
        if not drive or not match.group(2):
            return drive
        return drive + match.group(2)
<|end_body_1|>

Solution:
class DosDriveMap:
    """Maps \\Device\\HarddiskVolumeN to N: on Windows."""

    def __init__(self):
        """Lazy loads the cache."""
        if not self._MAPPING:
            self._MAPPING['\\Device\\Mup'] = None
            self._MAPPING['\\SystemRoot'] = os.environ['SystemRoot']
            for letter in (chr(l) for l in range(ord('C'), ord('Z') + 1)):
                try:
                    letter = '%s:' % letter
                    mapped = QueryDosDevice(letter)
                    if mapped in self._MAPPING:
                        logging.warning("Two drives: '%s' and '%s', are mapped to the same disk. Drive letters are a user-mode concept and the kernel traces only have NT path, so all accesses will be associated with the first drive letter, independent of the actual letter used by the code" % (self._MAPPING[mapped], letter))
                    else:
                        self._MAPPING[mapped] = letter
                except WindowsError:
                    pass

    def to_win32(self, path):
        """Converts a native NT path to Win32/DOS compatible path."""
        match = re.match('(^\\\\Device\\\\[a-zA-Z0-9]+)(\\\\.*)?$', path)
        if not match:
            raise ValueError("Can't convert %s into a Win32 compatible path" % path, path)
        if not match.group(1) in self._MAPPING:
            return None
        drive = self._MAPPING[match.group(1)]
        if not drive or not match.group(2):
            return drive
        return drive + match.group(2)


merge

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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def merge(self, intervals): :type intervals: List[List[int]] :rtype: List[List[int]]
- def merge0(self, intervals): :type intervals: List[List[int]] :rtype: List[List[int]]

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def merge(self, intervals): :type intervals: List[List[int]] :rtype: List[List[int]]
- def merge0(self, intervals): :type intervals: List[List[int]] :rtype: List[List[int]]

<|skeleton|>
class Solution:

    def merge(self, intervals):
        """:type intervals: List[List[int]] :rtype: List[List[int]]"""
        <|body_0|>

    def merge0(self, intervals):
        """:type intervals: List[List[int]] :rtype: List[List[int]]"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        n = len(intervals)
        if n <= 1:
            return intervals
        intervals = sorted(intervals, key=lambda x: x[0])
        stack = []
        for i in range(0, len(intervals)):
            start = intervals[i][0]
            if stack and stack[-1][1] >= start:
                stack[-1][1] = max(stack[-1][1], intervals[i][1])
            else:
                stack.append([start, intervals[i][1]])
        return stack
<|end_body_0|>

<|body_start_1|>
        n = len(intervals)
        if n <= 1:
            return intervals
        intervals = sorted(intervals, key=lambda x: x[1])
        stack = []
        for i in range(0, len(intervals)):
            start = intervals[i][0]
            while stack and stack[-1][1] >= intervals[i][0]:
                start = min(stack[-1][0], intervals[i][0])
                stack.pop()
            stack.append([start, intervals[i][1]])
        return stack
<|end_body_1|>

Solution:
class Solution:
    def merge(self, intervals):
        """:type intervals: List[List[int]] :rtype: List[List[int]]"""
        n = len(intervals)
        if n <= 1:
            return intervals
        intervals = sorted(intervals, key=lambda x: x[0])
        stack = []
        for i in range(0, len(intervals)):
            start = intervals[i][0]
            if stack and stack[-1][1] >= start:
                stack[-1][1] = max(stack[-1][1], intervals[i][1])
            else:
                stack.append([start, intervals[i][1]])
        return stack

    def merge0(self, intervals):
        """:type intervals: List[List[int]] :rtype: List[List[int]]"""
        n = len(intervals)
        if n <= 1:
            return intervals
        intervals = sorted(intervals, key=lambda x: x[1])
        stack = []
        for i in range(0, len(intervals)):
            start = intervals[i][0]
            while stack and stack[-1][1] >= intervals[i][0]:
                start = min(stack[-1][0], intervals[i][0])
                stack.pop()
            stack.append([start, intervals[i][1]])
        return stack


createHistoryMenu

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

Class description:
Controls the tool bar view including navigation in item history.

Method signatures and docstrings:
- def __init__(self, forwardAction, backwardAction, parentDirectoryAction, refreshAction, toolbarAction, widget, mainWindow, parentController): Constructor.
- def setActivated(self, activated): Activates or deactivates of the tool bar.
- def createHistoryMenu(self, pathlist, menu, iterator): Create a menu from the given list with L{QtCore.QModelIndex} objects. @param pathlist: List of history paths objects. @type pathlist: C{list} @param menu: Menu to which the given path list will added to. @type menu: C{QtGui.QMenu} @param iterator: The iterator that specifies if the menu will move relative forward or backward. @type iterator: C{int}
- def _createJumpToPathActionSlot(self, action): Creates a slot which directly jumps to the associated path in the history.

Implement the Python class `ToolbarController` described below.

Class description:
Controls the tool bar view including navigation in item history.

Method signatures and docstrings:
- def __init__(self, forwardAction, backwardAction, parentDirectoryAction, refreshAction, toolbarAction, widget, mainWindow, parentController): Constructor.
- def setActivated(self, activated): Activates or deactivates of the tool bar.
- def createHistoryMenu(self, pathlist, menu, iterator): Create a menu from the given list with L{QtCore.QModelIndex} objects. @param pathlist: List of history paths objects. @type pathlist: C{list} @param menu: Menu to which the given path list will added to. @type menu: C{QtGui.QMenu} @param iterator: The iterator that specifies if the menu will move relative forward or backward. @type iterator: C{int}
- def _createJumpToPathActionSlot(self, action): Creates a slot which directly jumps to the associated path in the history.

<|skeleton|>
class ToolbarController:
    """Controls the tool bar view including navigation in item history."""

    def __init__(self, forwardAction, backwardAction, parentDirectoryAction, refreshAction, toolbarAction, widget, mainWindow, parentController):
        """Constructor."""
        <|body_0|>

    def setActivated(self, activated):
        """Activates or deactivates of the tool bar."""
        <|body_1|>

    def createHistoryMenu(self, pathlist, menu, iterator):
        """Create a menu from the given list with L{QtCore.QModelIndex} objects. @param pathlist: List of history paths objects. @type pathlist: C{list} @param menu: Menu to which the given path list will added to. @type menu: C{QtGui.QMenu} @param iterator: The iterator that specifies if the menu will move relative forward or backward. @type iterator: C{int}"""
        <|body_2|>

    def _createJumpToPathActionSlot(self, action):
        """Creates a slot which directly jumps to the associated path in the history."""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        AbstractController.__init__(self, widget, mainWindow, parentController=parentController)
        self._toolbarAction = toolbarAction
        self.forwardAction = forwardAction
        self.forwardMenu = QtGui.QMenu(widget)
        self.forwardAction.setData(QtCore.QVariant(1))
        self.forwardAction.setMenu(self.forwardMenu)
        self.backwardAction = backwardAction
        self.backwardMenu = QtGui.QMenu(widget)
        self.backwardAction.setData(QtCore.QVariant(-1))
        self.backwardAction.setMenu(self.backwardMenu)
        self.parentDirectoryAction = parentDirectoryAction
        self.refreshAction = refreshAction
        self._delegate = _ToolbarDelegate(self)
        self.setActivated(False)
<|end_body_0|>

<|body_start_1|>
        self.widget.setEnabled(activated)
        if activated:
            self.forwardAction.setEnabled(not activated)
            self.backwardAction.setEnabled(not activated)
            self.parentDirectoryAction.setEnabled(not activated)
            self.refreshAction.setEnabled(activated)
        else:
            self.forwardAction.setEnabled(activated)
            self.backwardAction.setEnabled(activated)
            self.parentDirectoryAction.setEnabled(activated)
            self.refreshAction.setEnabled(activated)
<|end_body_1|>

<|body_start_2|>
        menu.clear()
        for steps, path in enumerate(pathlist):
            action = QtGui.QAction(path, menu)
            action.setData(QtCore.QVariant((steps + 1) * iterator))
            QtCore.QObject.connect(action, QtCore.SIGNAL('triggered()'), self._createJumpToPathActionSlot(action))
            menu.addAction(action)
        if len(pathlist):
            menu.setDefaultAction(menu.actions()[0])
<|end_body_2|>

<|body_start_3|>
        def _jumpToPathActionSlot():
            steps, success = action.data().toInt()
            if success:
                self.model.relativeHistoryIndex = steps
        return _jumpToPathActionSlot
<|end_body_3|>

Solution:
class ToolbarController:
    """Controls the tool bar view including navigation in item history."""

    def __init__(self, forwardAction, backwardAction, parentDirectoryAction, refreshAction, toolbarAction, widget, mainWindow, parentController):
        """Constructor."""
        AbstractController.__init__(self, widget, mainWindow, parentController=parentController)
        self._toolbarAction = toolbarAction
        self.forwardAction = forwardAction
        self.forwardMenu = QtGui.QMenu(widget)
        self.forwardAction.setData(QtCore.QVariant(1))
        self.forwardAction.setMenu(self.forwardMenu)
        self.backwardAction = backwardAction
        self.backwardMenu = QtGui.QMenu(widget)
        self.backwardAction.setData(QtCore.QVariant(-1))
        self.backwardAction.setMenu(self.backwardMenu)
        self.parentDirectoryAction = parentDirectoryAction
        self.refreshAction = refreshAction
        self._delegate = _ToolbarDelegate(self)
        self.setActivated(False)

    def setActivated(self, activated):
        """Activates or deactivates of the tool bar."""
        self.widget.setEnabled(activated)
        if activated:
            self.forwardAction.setEnabled(not activated)
            self.backwardAction.setEnabled(not activated)
            self.parentDirectoryAction.setEnabled(not activated)
            self.refreshAction.setEnabled(activated)
        else:
            self.forwardAction.setEnabled(activated)
            self.backwardAction.setEnabled(activated)
            self.parentDirectoryAction.setEnabled(activated)
            self.refreshAction.setEnabled(activated)

    def createHistoryMenu(self, pathlist, menu, iterator):
        """Create a menu from the given list with L{QtCore.QModelIndex} objects. @param pathlist: List of history paths objects. @type pathlist: C{list} @param menu: Menu to which the given path list will added to. @type menu: C{QtGui.QMenu} @param iterator: The iterator that specifies if the menu will move relative forward or backward. @type iterator: C{int}"""
        menu.clear()
        for steps, path in enumerate(pathlist):
            action = QtGui.QAction(path, menu)
            action.setData(QtCore.QVariant((steps + 1) * iterator))
            QtCore.QObject.connect(action, QtCore.SIGNAL('triggered()'), self._createJumpToPathActionSlot(action))
            menu.addAction(action)
        if len(pathlist):
            menu.setDefaultAction(menu.actions()[0])

    def _createJumpToPathActionSlot(self, action):
        """Creates a slot which directly jumps to the associated path in the history."""
        def _jumpToPathActionSlot():
            steps, success = action.data().toInt()
            if success:
                self.model.relativeHistoryIndex = steps
        return _jumpToPathActionSlot


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

Class description:
Implement the RentalSchema class.

Method signatures and docstrings:
- def assert_end_time_with_price(self, data, **kwargs): Asserts that when a rental is complete both the price and end time are included.
- def assert_url_included_with_foreign_key(self, data, **kwargs): Asserts that when a user_id or bike_id is sent that a user_url or bike_url is sent with it.

Implement the Python class `RentalSchema` described below.

Class description:
Implement the RentalSchema class.

Method signatures and docstrings:
- def assert_end_time_with_price(self, data, **kwargs): Asserts that when a rental is complete both the price and end time are included.
- def assert_url_included_with_foreign_key(self, data, **kwargs): Asserts that when a user_id or bike_id is sent that a user_url or bike_url is sent with it.

<|skeleton|>
class RentalSchema:

    def assert_end_time_with_price(self, data, **kwargs):
        """Asserts that when a rental is complete both the price and end time are included."""
        <|body_0|>

    def assert_url_included_with_foreign_key(self, data, **kwargs):
        """Asserts that when a user_id or bike_id is sent that a user_url or bike_url is sent with it."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        if 'price' in data and 'end_time' not in data:
            raise ValidationError('If the price is included, you must also include the end time.')
        elif 'price' not in data and 'end_time' in data:
            raise ValidationError('If the end time is included, you must also include the price.')
        if 'price' in data and 'estimated_price' in data:
            raise ValidationError('Rental should have one of either price or estimated_price.')
<|end_body_0|>

<|body_start_1|>
        if 'user_id' in data and 'user_url' not in data:
            raise ValidationError('User ID was included, but User URL was not.')
        if 'bike_id' in data and 'bike_url' not in data:
            raise ValidationError('Bike ID was included, but Bike URL was not.')
<|end_body_1|>

Solution:
class RentalSchema:
    def assert_end_time_with_price(self, data, **kwargs):
        """Asserts that when a rental is complete both the price and end time are included."""
        if 'price' in data and 'end_time' not in data:
            raise ValidationError('If the price is included, you must also include the end time.')
        elif 'price' not in data and 'end_time' in data:
            raise ValidationError('If the end time is included, you must also include the price.')
        if 'price' in data and 'estimated_price' in data:
            raise ValidationError('Rental should have one of either price or estimated_price.')

    def assert_url_included_with_foreign_key(self, data, **kwargs):
        """Asserts that when a user_id or bike_id is sent that a user_url or bike_url is sent with it."""
        if 'user_id' in data and 'user_url' not in data:
            raise ValidationError('User ID was included, but User URL was not.')
        if 'bike_id' in data and 'bike_url' not in data:
            raise ValidationError('Bike ID was included, but Bike URL was not.')


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

Class description:
Represents the attempt to run from a battle.

Method signatures and docstrings:
- def __init__(self, pokemon: PokemonModel, opponent_pokemon: PokemonModel) -> None: Create a new run action. :param pokemon: The pokemon trying to escape. :param opponent_pokemon: The other pokemon.
- def is_run_successful(self) -> None: Determine whether the pokemon succeed in escaping from the battle. :return True if the pokemon escapes.

Implement the Python class `RunActionModel` described below.

Class description:
Represents the attempt to run from a battle.

Method signatures and docstrings:
- def __init__(self, pokemon: PokemonModel, opponent_pokemon: PokemonModel) -> None: Create a new run action. :param pokemon: The pokemon trying to escape. :param opponent_pokemon: The other pokemon.
- def is_run_successful(self) -> None: Determine whether the pokemon succeed in escaping from the battle. :return True if the pokemon escapes.

<|skeleton|>
class RunActionModel:
    """Represents the attempt to run from a battle."""

    def __init__(self, pokemon: PokemonModel, opponent_pokemon: PokemonModel) -> None:
        """Create a new run action. :param pokemon: The pokemon trying to escape. :param opponent_pokemon: The other pokemon."""
        <|body_0|>

    def is_run_successful(self) -> None:
        """Determine whether the pokemon succeed in escaping from the battle. :return True if the pokemon escapes."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self._pokemon = pokemon
        self._opponent_pokemon = opponent_pokemon
        self._is_run_successful = None
<|end_body_0|>

<|body_start_1|>
        if self._is_run_successful is None:
            F = (self._pokemon.stats[StatEnum.SPEED] * 128 / self._opponent_pokemon.stats[StatEnum.SPEED] + 30) % 256
            self._is_run_successful = F > random.randint(0, 255)
        return self._is_run_successful
<|end_body_1|>

Solution:
class RunActionModel:
    """Represents the attempt to run from a battle."""

    def __init__(self, pokemon: PokemonModel, opponent_pokemon: PokemonModel) -> None:
        """Create a new run action. :param pokemon: The pokemon trying to escape. :param opponent_pokemon: The other pokemon."""
        self._pokemon = pokemon
        self._opponent_pokemon = opponent_pokemon
        self._is_run_successful = None

    def is_run_successful(self) -> None:
        """Determine whether the pokemon succeed in escaping from the battle. :return True if the pokemon escapes."""
        if self._is_run_successful is None:
            F = (self._pokemon.stats[StatEnum.SPEED] * 128 / self._opponent_pokemon.stats[StatEnum.SPEED] + 30) % 256
            self._is_run_successful = F > random.randint(0, 255)
        return self._is_run_successful


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

Class description:
Virtual chromite module If the checkout is not named 'chromite', trying to do 'from chromite.xxx' to import modules fails horribly. Instead, manually locate the chromite directory (whatever it is named), load & return it whenever someone tries to import it. This lets us use the stable name 'chromite' regardless of how things are structured on disk. This also lets us keep the sys.path search clean. Otherwise we'd have to worry about what other dirs chromite were checked out near to as doing an import would also search those for .py modules.

Method signatures and docstrings:
- def find_module(self, fullname, _path=None): Handle the 'chromite' module
- def load_module(self, _fullname): Return our cache of the 'chromite' module

Implement the Python class `ChromiteImporter` described below.

Class description:
Virtual chromite module If the checkout is not named 'chromite', trying to do 'from chromite.xxx' to import modules fails horribly. Instead, manually locate the chromite directory (whatever it is named), load & return it whenever someone tries to import it. This lets us use the stable name 'chromite' regardless of how things are structured on disk. This also lets us keep the sys.path search clean. Otherwise we'd have to worry about what other dirs chromite were checked out near to as doing an import would also search those for .py modules.

Method signatures and docstrings:
- def find_module(self, fullname, _path=None): Handle the 'chromite' module
- def load_module(self, _fullname): Return our cache of the 'chromite' module

<|skeleton|>
class ChromiteImporter:
    """Virtual chromite module If the checkout is not named 'chromite', trying to do 'from chromite.xxx' to import modules fails horribly. Instead, manually locate the chromite directory (whatever it is named), load & return it whenever someone tries to import it. This lets us use the stable name 'chromite' regardless of how things are structured on disk. This also lets us keep the sys.path search clean. Otherwise we'd have to worry about what other dirs chromite were checked out near to as doing an import would also search those for .py modules."""

    def find_module(self, fullname, _path=None):
        """Handle the 'chromite' module"""
        <|body_0|>

    def load_module(self, _fullname):
        """Return our cache of the 'chromite' module"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        if fullname == 'chromite' and (not self._loading):
            return self
        return None
<|end_body_0|>

<|body_start_1|>
        path = os.path.dirname(os.path.realpath(__file__))
        while not os.path.exists(os.path.join(path, 'PRESUBMIT.cfg')):
            path = os.path.dirname(path)
        global CHROMITE_PATH
        CHROMITE_PATH = path + '/'
        path, mod = os.path.split(path)
        sys.path.insert(0, path)
        self._loading = True
        try:
            return __import__(mod)
        finally:
            sys.path.remove(path)
            self._loading = False
<|end_body_1|>

Solution:
class ChromiteImporter:
    """Virtual chromite module If the checkout is not named 'chromite', trying to do 'from chromite.xxx' to import modules fails horribly. Instead, manually locate the chromite directory (whatever it is named), load & return it whenever someone tries to import it. This lets us use the stable name 'chromite' regardless of how things are structured on disk. This also lets us keep the sys.path search clean. Otherwise we'd have to worry about what other dirs chromite were checked out near to as doing an import would also search those for .py modules."""

    def find_module(self, fullname, _path=None):
        """Handle the 'chromite' module"""
        if fullname == 'chromite' and (not self._loading):
            return self
        return None

    def load_module(self, _fullname):
        """Return our cache of the 'chromite' module"""
        path = os.path.dirname(os.path.realpath(__file__))
        while not os.path.exists(os.path.join(path, 'PRESUBMIT.cfg')):
            path = os.path.dirname(path)
        global CHROMITE_PATH
        CHROMITE_PATH = path + '/'
        path, mod = os.path.split(path)
        sys.path.insert(0, path)
        self._loading = True
        try:
            return __import__(mod)
        finally:
            sys.path.remove(path)
            self._loading = False


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

Class description:
Samples DensePose data from DensePose predictions. Samples for each class are drawn using confidence value estimates.

Method signatures and docstrings:
- def __init__(self, confidence_channel: str, count_per_class: int=8, search_count_multiplier: Optional[float]=None, search_proportion: Optional[float]=None): Constructor Args: confidence_channel (str): confidence channel to use for sampling; possible values: "sigma_2": confidences for UV values "fine_segm_confidence": confidences for fine segmentation "coarse_segm_confidence": confidences for coarse segmentation (default: "sigma_2") count_per_class (int): the sampler produces at most `count_per_class` samples for each category (default: 8) search_count_multiplier (float or None): if not None, the total number of the most confident estimates of a given class to consider is defined as `min(search_count_multiplier * count_per_class, N)`, where `N` is the total number of estimates of the class; cannot be specified together with `search_proportion` (d
- def _produce_index_sample(self, values: torch.Tensor, count: int): Produce a sample of indices to select data based on confidences Args: values (torch.Tensor): an array of size [n, k] that contains estimated values (U, V, confidences); n: number of channels (U, V, confidences) k: number of points labeled with part_id count (int): number of samples to produce, should be positive and <= k Return: list(int): indices of values (along axis 1) selected as a sample
- def _produce_labels_and_results(self, instance) -> Tuple[torch.Tensor, torch.Tensor]: Method to get labels and DensePose results from an instance, with confidences Args: instance (Instances): an instance of `DensePoseChartPredictorOutputWithConfidences` Return: labels (torch.Tensor): shape [H, W], DensePose segmentation labels dp_result (torch.Tensor): shape [3, H, W], DensePose results u and v stacked with the confidence channel

Implement the Python class `DensePoseConfidenceBasedSampler` described below.

Class description:
Samples DensePose data from DensePose predictions. Samples for each class are drawn using confidence value estimates.

Method signatures and docstrings:
- def __init__(self, confidence_channel: str, count_per_class: int=8, search_count_multiplier: Optional[float]=None, search_proportion: Optional[float]=None): Constructor Args: confidence_channel (str): confidence channel to use for sampling; possible values: "sigma_2": confidences for UV values "fine_segm_confidence": confidences for fine segmentation "coarse_segm_confidence": confidences for coarse segmentation (default: "sigma_2") count_per_class (int): the sampler produces at most `count_per_class` samples for each category (default: 8) search_count_multiplier (float or None): if not None, the total number of the most confident estimates of a given class to consider is defined as `min(search_count_multiplier * count_per_class, N)`, where `N` is the total number of estimates of the class; cannot be specified together with `search_proportion` (d
- def _produce_index_sample(self, values: torch.Tensor, count: int): Produce a sample of indices to select data based on confidences Args: values (torch.Tensor): an array of size [n, k] that contains estimated values (U, V, confidences); n: number of channels (U, V, confidences) k: number of points labeled with part_id count (int): number of samples to produce, should be positive and <= k Return: list(int): indices of values (along axis 1) selected as a sample
- def _produce_labels_and_results(self, instance) -> Tuple[torch.Tensor, torch.Tensor]: Method to get labels and DensePose results from an instance, with confidences Args: instance (Instances): an instance of `DensePoseChartPredictorOutputWithConfidences` Return: labels (torch.Tensor): shape [H, W], DensePose segmentation labels dp_result (torch.Tensor): shape [3, H, W], DensePose results u and v stacked with the confidence channel

<|skeleton|>
class DensePoseConfidenceBasedSampler:
    """Samples DensePose data from DensePose predictions. Samples for each class are drawn using confidence value estimates."""

    def __init__(self, confidence_channel: str, count_per_class: int=8, search_count_multiplier: Optional[float]=None, search_proportion: Optional[float]=None):
        """Constructor Args: confidence_channel (str): confidence channel to use for sampling; possible values: "sigma_2": confidences for UV values "fine_segm_confidence": confidences for fine segmentation "coarse_segm_confidence": confidences for coarse segmentation (default: "sigma_2") count_per_class (int): the sampler produces at most `count_per_class` samples for each category (default: 8) search_count_multiplier (float or None): if not None, the total number of the most confident estimates of a given class to consider is defined as `min(search_count_multiplier * count_per_class, N)`, where `N` is the total number of estimates of the class; cannot be specified together with `search_proportion` (d"""
        <|body_0|>

    def _produce_index_sample(self, values: torch.Tensor, count: int):
        """Produce a sample of indices to select data based on confidences Args: values (torch.Tensor): an array of size [n, k] that contains estimated values (U, V, confidences); n: number of channels (U, V, confidences) k: number of points labeled with part_id count (int): number of samples to produce, should be positive and <= k Return: list(int): indices of values (along axis 1) selected as a sample"""
        <|body_1|>

    def _produce_labels_and_results(self, instance) -> Tuple[torch.Tensor, torch.Tensor]:
        """Method to get labels and DensePose results from an instance, with confidences Args: instance (Instances): an instance of `DensePoseChartPredictorOutputWithConfidences` Return: labels (torch.Tensor): shape [H, W], DensePose segmentation labels dp_result (torch.Tensor): shape [3, H, W], DensePose results u and v stacked with the confidence channel"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        super().__init__(count_per_class)
        self.confidence_channel = confidence_channel
        self.search_count_multiplier = search_count_multiplier
        self.search_proportion = search_proportion
        assert search_count_multiplier is None or search_proportion is None, f'Cannot specify both search_count_multiplier (={search_count_multiplier})and search_proportion (={search_proportion})'
<|end_body_0|>

<|body_start_1|>
        k = values.shape[1]
        if k == count:
            index_sample = list(range(k))
        else:
            _, sorted_confidence_indices = torch.sort(values[2])
            if self.search_count_multiplier is not None:
                search_count = min(int(count * self.search_count_multiplier), k)
            elif self.search_proportion is not None:
                search_count = min(max(int(k * self.search_proportion), count), k)
            else:
                search_count = min(count, k)
            sample_from_top = random.sample(range(search_count), count)
            index_sample = sorted_confidence_indices[:search_count][sample_from_top]
        return index_sample
<|end_body_1|>

<|body_start_2|>
        converter = ToChartResultConverterWithConfidences
        chart_result = converter.convert(instance.pred_densepose, instance.pred_boxes)
        labels, dp_result = (chart_result.labels.cpu(), chart_result.uv.cpu())
        dp_result = torch.cat((dp_result, getattr(chart_result, self.confidence_channel)[None].cpu()))
        return (labels, dp_result)
<|end_body_2|>

Solution:
class DensePoseConfidenceBasedSampler:
    """Samples DensePose data from DensePose predictions. Samples for each class are drawn using confidence value estimates."""

    def __init__(self, confidence_channel: str, count_per_class: int=8, search_count_multiplier: Optional[float]=None, search_proportion: Optional[float]=None):
        """Constructor Args: confidence_channel (str): confidence channel to use for sampling; possible values: "sigma_2": confidences for UV values "fine_segm_confidence": confidences for fine segmentation "coarse_segm_confidence": confidences for coarse segmentation (default: "sigma_2") count_per_class (int): the sampler produces at most `count_per_class` samples for each category (default: 8) search_count_multiplier (float or None): if not None, the total number of the most confident estimates of a given class to consider is defined as `min(search_count_multiplier * count_per_class, N)`, where `N` is the total number of estimates of the class; cannot be specified together with `search_proportion` (d"""
        super().__init__(count_per_class)
        self.confidence_channel = confidence_channel
        self.search_count_multiplier = search_count_multiplier
        self.search_proportion = search_proportion
        assert search_count_multiplier is None or search_proportion is None, f'Cannot specify both search_count_multiplier (={search_count_multiplier})and search_proportion (={search_proportion})'

    def _produce_index_sample(self, values: torch.Tensor, count: int):
        """Produce a sample of indices to select data based on confidences Args: values (torch.Tensor): an array of size [n, k] that contains estimated values (U, V, confidences); n: number of channels (U, V, confidences) k: number of points labeled with part_id count (int): number of samples to produce, should be positive and <= k Return: list(int): indices of values (along axis 1) selected as a sample"""
        k = values.shape[1]
        if k == count:
            index_sample = list(range(k))
        else:
            _, sorted_confidence_indices = torch.sort(values[2])
            if self.search_count_multiplier is not None:
                search_count = min(int(count * self.search_count_multiplier), k)
            elif self.search_proportion is not None:
                search_count = min(max(int(k * self.search_proportion), count), k)
            else:
                search_count = min(count, k)
            sample_from_top = random.sample(range(search_count), count)
            index_sample = sorted_confidence_indices[:search_count][sample_from_top]
        return index_sample

    def _produce_labels_and_results(self, instance) -> Tuple[torch.Tensor, torch.Tensor]:
        """Method to get labels and DensePose results from an instance, with confidences Args: instance (Instances): an instance of `DensePoseChartPredictorOutputWithConfidences` Return: labels (torch.Tensor): shape [H, W], DensePose segmentation labels dp_result (torch.Tensor): shape [3, H, W], DensePose results u and v stacked with the confidence channel"""
        converter = ToChartResultConverterWithConfidences
        chart_result = converter.convert(instance.pred_densepose, instance.pred_boxes)
        labels, dp_result = (chart_result.labels.cpu(), chart_result.uv.cpu())
        dp_result = torch.cat((dp_result, getattr(chart_result, self.confidence_channel)[None].cpu()))
        return (labels, dp_result)


evolve

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

Class description:
A simulation of diffusion

Method signatures and docstrings:
- def initialize(self): Initialize the grid and variables for diffusion and set the initial conditions for the chosen problem.
- def method_compute_timestep(self): The diffusion timestep() function computes the timestep using the explicit timestep constraint as the starting point. We then multiply by the CFL number to get the timestep. Since we are doing an implicit discretization, we do not require CFL < 1.
- def evolve(self): Diffusion through dt using C-N implicit solve with multigrid
- def dovis(self): Do runtime visualization.

Implement the Python class `Simulation` described below.

Class description:
A simulation of diffusion

Method signatures and docstrings:
- def initialize(self): Initialize the grid and variables for diffusion and set the initial conditions for the chosen problem.
- def method_compute_timestep(self): The diffusion timestep() function computes the timestep using the explicit timestep constraint as the starting point. We then multiply by the CFL number to get the timestep. Since we are doing an implicit discretization, we do not require CFL < 1.
- def evolve(self): Diffusion through dt using C-N implicit solve with multigrid
- def dovis(self): Do runtime visualization.

<|skeleton|>
class Simulation:
    """A simulation of diffusion"""

    def initialize(self):
        """Initialize the grid and variables for diffusion and set the initial conditions for the chosen problem."""
        <|body_0|>

    def method_compute_timestep(self):
        """The diffusion timestep() function computes the timestep using the explicit timestep constraint as the starting point. We then multiply by the CFL number to get the timestep. Since we are doing an implicit discretization, we do not require CFL < 1."""
        <|body_1|>

    def evolve(self):
        """Diffusion through dt using C-N implicit solve with multigrid"""
        <|body_2|>

    def dovis(self):
        """Do runtime visualization."""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        my_grid = grid_setup(self.rp, ng=1)
        if my_grid.nx != my_grid.ny:
            msg.fail('need nx = ny for diffusion problems')
        n = int(math.log(my_grid.nx) / math.log(2.0))
        if 2 ** n != my_grid.nx:
            msg.fail('grid needs to be a power of 2')
        bc, _, _ = bc_setup(self.rp)
        for bnd in [bc.xlb, bc.xrb, bc.ylb, bc.yrb]:
            if bnd not in ['periodic', 'neumann', 'dirichlet']:
                msg.fail('invalid BC')
        my_data = patch.CellCenterData2d(my_grid)
        my_data.register_var('phi', bc)
        my_data.create()
        self.cc_data = my_data
        problem = importlib.import_module(f'pyro.diffusion.problems.{self.problem_name}')
        problem.init_data(self.cc_data, self.rp)
<|end_body_0|>

<|body_start_1|>
        cfl = self.rp.get_param('driver.cfl')
        k = self.rp.get_param('diffusion.k')
        xtmp = self.cc_data.grid.dx ** 2 / k
        ytmp = self.cc_data.grid.dy ** 2 / k
        self.dt = cfl * min(xtmp, ytmp)
<|end_body_1|>

<|body_start_2|>
        self.cc_data.fill_BC_all()
        phi = self.cc_data.get_var('phi')
        myg = self.cc_data.grid
        k = self.rp.get_param('diffusion.k')
        mg = MG.CellCenterMG2d(myg.nx, myg.ny, xmin=myg.xmin, xmax=myg.xmax, ymin=myg.ymin, ymax=myg.ymax, xl_BC_type=self.cc_data.BCs['phi'].xlb, xr_BC_type=self.cc_data.BCs['phi'].xrb, yl_BC_type=self.cc_data.BCs['phi'].ylb, yr_BC_type=self.cc_data.BCs['phi'].yrb, alpha=1.0, beta=0.5 * self.dt * k, verbose=0)
        f = mg.soln_grid.scratch_array()
        f.v()[:, :] = phi.v() + 0.5 * self.dt * k * ((phi.ip(1) + phi.ip(-1) - 2.0 * phi.v()) / myg.dx ** 2 + (phi.jp(1) + phi.jp(-1) - 2.0 * phi.v()) / myg.dy ** 2)
        mg.init_RHS(f)
        mg.init_zeros()
        mg.solve(rtol=1e-10)
        phi.v()[:, :] = mg.get_solution().v()
        self.cc_data.t += self.dt
        self.n += 1
<|end_body_2|>

<|body_start_3|>
        plt.clf()
        phi = self.cc_data.get_var('phi')
        myg = self.cc_data.grid
        img = plt.imshow(np.transpose(phi.v()), interpolation='nearest', origin='lower', extent=[myg.xmin, myg.xmax, myg.ymin, myg.ymax], cmap=self.cm)
        plt.xlabel('x')
        plt.ylabel('y')
        plt.title('phi')
        cb = plt.colorbar(img)
        cb.formatter = matplotlib.ticker.FormatStrFormatter('')
        plt.figtext(0.05, 0.0125, f't = {self.cc_data.t:10.5f}')
        plt.pause(0.001)
        plt.draw()
<|end_body_3|>

Solution:
class Simulation:
    """A simulation of diffusion"""

    def initialize(self):
        """Initialize the grid and variables for diffusion and set the initial conditions for the chosen problem."""
        my_grid = grid_setup(self.rp, ng=1)
        if my_grid.nx != my_grid.ny:
            msg.fail('need nx = ny for diffusion problems')
        n = int(math.log(my_grid.nx) / math.log(2.0))
        if 2 ** n != my_grid.nx:
            msg.fail('grid needs to be a power of 2')
        bc, _, _ = bc_setup(self.rp)
        for bnd in [bc.xlb, bc.xrb, bc.ylb, bc.yrb]:
            if bnd not in ['periodic', 'neumann', 'dirichlet']:
                msg.fail('invalid BC')
        my_data = patch.CellCenterData2d(my_grid)
        my_data.register_var('phi', bc)
        my_data.create()
        self.cc_data = my_data
        problem = importlib.import_module(f'pyro.diffusion.problems.{self.problem_name}')
        problem.init_data(self.cc_data, self.rp)

    def method_compute_timestep(self):
        """The diffusion timestep() function computes the timestep using the explicit timestep constraint as the starting point. We then multiply by the CFL number to get the timestep. Since we are doing an implicit discretization, we do not require CFL < 1."""
        cfl = self.rp.get_param('driver.cfl')
        k = self.rp.get_param('diffusion.k')
        xtmp = self.cc_data.grid.dx ** 2 / k
        ytmp = self.cc_data.grid.dy ** 2 / k
        self.dt = cfl * min(xtmp, ytmp)

    def evolve(self):
        """Diffusion through dt using C-N implicit solve with multigrid"""
        self.cc_data.fill_BC_all()
        phi = self.cc_data.get_var('phi')
        myg = self.cc_data.grid
        k = self.rp.get_param('diffusion.k')
        mg = MG.CellCenterMG2d(myg.nx, myg.ny, xmin=myg.xmin, xmax=myg.xmax, ymin=myg.ymin, ymax=myg.ymax, xl_BC_type=self.cc_data.BCs['phi'].xlb, xr_BC_type=self.cc_data.BCs['phi'].xrb, yl_BC_type=self.cc_data.BCs['phi'].ylb, yr_BC_type=self.cc_data.BCs['phi'].yrb, alpha=1.0, beta=0.5 * self.dt * k, verbose=0)
        f = mg.soln_grid.scratch_array()
        f.v()[:, :] = phi.v() + 0.5 * self.dt * k * ((phi.ip(1) + phi.ip(-1) - 2.0 * phi.v()) / myg.dx ** 2 + (phi.jp(1) + phi.jp(-1) - 2.0 * phi.v()) / myg.dy ** 2)
        mg.init_RHS(f)
        mg.init_zeros()
        mg.solve(rtol=1e-10)
        phi.v()[:, :] = mg.get_solution().v()
        self.cc_data.t += self.dt
        self.n += 1

    def dovis(self):
        """Do runtime visualization."""
        plt.clf()
        phi = self.cc_data.get_var('phi')
        myg = self.cc_data.grid
        img = plt.imshow(np.transpose(phi.v()), interpolation='nearest', origin='lower', extent=[myg.xmin, myg.xmax, myg.ymin, myg.ymax], cmap=self.cm)
        plt.xlabel('x')
        plt.ylabel('y')
        plt.title('phi')
        cb = plt.colorbar(img)
        cb.formatter = matplotlib.ticker.FormatStrFormatter('')
        plt.figtext(0.05, 0.0125, f't = {self.cc_data.t:10.5f}')
        plt.pause(0.001)
        plt.draw()


insert

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

Class description:
Implement the Insert class.

Method signatures and docstrings:
- def insert_uniques(self, table, columns, values): Insert multiple rows into a table that do not already exist. If the rows primary key already exists, the rows values will be updated. If the rows primary key does not exists, a new row will be inserted
- def insert(self, table, columns, values, execute=True): Insert a single row into a table.
- def insert_many(self, table, columns, values, limit=MAX_ROWS_PER_QUERY, execute=True): Insert multiple rows into a table. If only one row is found, self.insert method will be used.

Implement the Python class `Insert` described below.

Class description:
Implement the Insert class.

Method signatures and docstrings:
- def insert_uniques(self, table, columns, values): Insert multiple rows into a table that do not already exist. If the rows primary key already exists, the rows values will be updated. If the rows primary key does not exists, a new row will be inserted
- def insert(self, table, columns, values, execute=True): Insert a single row into a table.
- def insert_many(self, table, columns, values, limit=MAX_ROWS_PER_QUERY, execute=True): Insert multiple rows into a table. If only one row is found, self.insert method will be used.

<|skeleton|>
class Insert:

    def insert_uniques(self, table, columns, values):
        """Insert multiple rows into a table that do not already exist. If the rows primary key already exists, the rows values will be updated. If the rows primary key does not exists, a new row will be inserted"""
        <|body_0|>

    def insert(self, table, columns, values, execute=True):
        """Insert a single row into a table."""
        <|body_1|>

    def insert_many(self, table, columns, values, limit=MAX_ROWS_PER_QUERY, execute=True):
        """Insert multiple rows into a table. If only one row is found, self.insert method will be used."""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        existing_rows = self.select(table, columns)
        unique = diff(existing_rows, values, y_only=True)
        keys = self.get_primary_key_vals(table)
        pk_col = self.get_primary_key(table)
        pk_index = columns.index(pk_col)
        to_insert, to_update = ([], [])
        for index, row in enumerate(unique):
            if row[pk_index] not in keys:
                to_insert.append(unique[index])
            elif row[pk_index] in keys:
                to_update.append(unique[index])
        if len(to_insert) > 0:
            self.insert_many(table, columns, to_insert)
        if len(to_update) > 0:
            self.update_many(table, columns, to_update, pk_col, 0)
        if len(to_insert) < 1 and len(to_update) < 0:
            self._printer('No rows added to', table)
<|end_body_0|>

<|body_start_1|>
        cols, vals = get_col_val_str(columns)
        statement = 'INSERT INTO {0} ({1}) VALUES ({2})'.format(wrap(table), cols, vals)
        if execute:
            self._cursor.execute(statement, values)
            self._commit()
            self._printer('\tMySQL row successfully inserted into {0}'.format(table))
        else:
            return statement
<|end_body_1|>

<|body_start_2|>
        if not isinstance(values[0], (list, set, tuple)):
            values = []
            for v in values:
                if v is not None and len(v) > 0:
                    values.append([v])
                else:
                    values.append([None])
        cols, vals = get_col_val_str(columns)
        statement = 'INSERT INTO {0} ({1}) VALUES ({2})'.format(wrap(table), cols, vals)
        if execute and len(values) > limit:
            while len(values) > 0:
                vals = [values.pop(0) for i in range(0, min(limit, len(values)))]
                self._cursor.executemany(statement, vals)
                self._commit()
        elif execute:
            self._cursor.executemany(statement, values)
            self._commit()
            self._printer('\tMySQL rows (' + str(len(values)) + ') successfully INSERTED')
        else:
            return statement
<|end_body_2|>

Solution:
class Insert:
    def insert_uniques(self, table, columns, values):
        """Insert multiple rows into a table that do not already exist. If the rows primary key already exists, the rows values will be updated. If the rows primary key does not exists, a new row will be inserted"""
        existing_rows = self.select(table, columns)
        unique = diff(existing_rows, values, y_only=True)
        keys = self.get_primary_key_vals(table)
        pk_col = self.get_primary_key(table)
        pk_index = columns.index(pk_col)
        to_insert, to_update = ([], [])
        for index, row in enumerate(unique):
            if row[pk_index] not in keys:
                to_insert.append(unique[index])
            elif row[pk_index] in keys:
                to_update.append(unique[index])
        if len(to_insert) > 0:
            self.insert_many(table, columns, to_insert)
        if len(to_update) > 0:
            self.update_many(table, columns, to_update, pk_col, 0)
        if len(to_insert) < 1 and len(to_update) < 0:
            self._printer('No rows added to', table)

    def insert(self, table, columns, values, execute=True):
        """Insert a single row into a table."""
        cols, vals = get_col_val_str(columns)
        statement = 'INSERT INTO {0} ({1}) VALUES ({2})'.format(wrap(table), cols, vals)
        if execute:
            self._cursor.execute(statement, values)
            self._commit()
            self._printer('\tMySQL row successfully inserted into {0}'.format(table))
        else:
            return statement

    def insert_many(self, table, columns, values, limit=MAX_ROWS_PER_QUERY, execute=True):
        """Insert multiple rows into a table. If only one row is found, self.insert method will be used."""
        if not isinstance(values[0], (list, set, tuple)):
            values = []
            for v in values:
                if v is not None and len(v) > 0:
                    values.append([v])
                else:
                    values.append([None])
        cols, vals = get_col_val_str(columns)
        statement = 'INSERT INTO {0} ({1}) VALUES ({2})'.format(wrap(table), cols, vals)
        if execute and len(values) > limit:
            while len(values) > 0:
                vals = [values.pop(0) for i in range(0, min(limit, len(values)))]
                self._cursor.executemany(statement, vals)
                self._commit()
        elif execute:
            self._cursor.executemany(statement, values)
            self._commit()
            self._printer('\tMySQL rows (' + str(len(values)) + ') successfully INSERTED')
        else:
            return statement


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

Class description:
Exclusion scope for a hook. An exclusion scope can be used to determine if a hook has been disabled for a specific project.

Method signatures and docstrings:
- def __init__(self, scope): Initialize. Args: scope: A list of shell-style wildcards (fnmatch) or regular expression. Regular expressions must start with the ^ character.
- def __contains__(self, proj_dir): Checks if |proj_dir| matches the excluded paths. Args: proj_dir: The relative path of the project.

Implement the Python class `ExclusionScope` described below.

Class description:
Exclusion scope for a hook. An exclusion scope can be used to determine if a hook has been disabled for a specific project.

Method signatures and docstrings:
- def __init__(self, scope): Initialize. Args: scope: A list of shell-style wildcards (fnmatch) or regular expression. Regular expressions must start with the ^ character.
- def __contains__(self, proj_dir): Checks if |proj_dir| matches the excluded paths. Args: proj_dir: The relative path of the project.

<|skeleton|>
class ExclusionScope:
    """Exclusion scope for a hook. An exclusion scope can be used to determine if a hook has been disabled for a specific project."""

    def __init__(self, scope):
        """Initialize. Args: scope: A list of shell-style wildcards (fnmatch) or regular expression. Regular expressions must start with the ^ character."""
        <|body_0|>

    def __contains__(self, proj_dir):
        """Checks if |proj_dir| matches the excluded paths. Args: proj_dir: The relative path of the project."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self._scope = []
        for path in scope:
            if path.startswith('^'):
                self._scope.append(re.compile(path))
            else:
                self._scope.append(path)
<|end_body_0|>

<|body_start_1|>
        for exclusion_path in self._scope:
            if hasattr(exclusion_path, 'match'):
                if exclusion_path.match(proj_dir):
                    return True
            elif fnmatch.fnmatch(proj_dir, exclusion_path):
                return True
        return False
<|end_body_1|>

Solution:
class ExclusionScope:
    """Exclusion scope for a hook. An exclusion scope can be used to determine if a hook has been disabled for a specific project."""

    def __init__(self, scope):
        """Initialize. Args: scope: A list of shell-style wildcards (fnmatch) or regular expression. Regular expressions must start with the ^ character."""
        self._scope = []
        for path in scope:
            if path.startswith('^'):
                self._scope.append(re.compile(path))
            else:
                self._scope.append(path)

    def __contains__(self, proj_dir):
        """Checks if |proj_dir| matches the excluded paths. Args: proj_dir: The relative path of the project."""
        for exclusion_path in self._scope:
            if hasattr(exclusion_path, 'match'):
                if exclusion_path.match(proj_dir):
                    return True
            elif fnmatch.fnmatch(proj_dir, exclusion_path):
                return True
        return False


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

Class description:
Position slider, including labels for the current position and duration. Attributes: widget: Widget containing the slider and labels. slider: Slider for seeking. This is public for use in tests only.

Method signatures and docstrings:
- def __init__(self, *, pubsub_bus: pubsub.PubSub, player_: player.Player) -> None: Initializer. Args: pubsub_bus: PubSub message bus. player_: Player.
- def _handle_play_status(self, status: player.PlayStatus) -> None: Handler for PlayStatus updates.
- def on_slider_change_value(self, slider: Gtk.Scale, scroll: Gtk.ScrollType, value: float) -> bool: Handler for the slider's change-value signal.

Implement the Python class `PositionSlider` described below.

Class description:
Position slider, including labels for the current position and duration. Attributes: widget: Widget containing the slider and labels. slider: Slider for seeking. This is public for use in tests only.

Method signatures and docstrings:
- def __init__(self, *, pubsub_bus: pubsub.PubSub, player_: player.Player) -> None: Initializer. Args: pubsub_bus: PubSub message bus. player_: Player.
- def _handle_play_status(self, status: player.PlayStatus) -> None: Handler for PlayStatus updates.
- def on_slider_change_value(self, slider: Gtk.Scale, scroll: Gtk.ScrollType, value: float) -> bool: Handler for the slider's change-value signal.

<|skeleton|>
class PositionSlider:
    """Position slider, including labels for the current position and duration. Attributes: widget: Widget containing the slider and labels. slider: Slider for seeking. This is public for use in tests only."""

    def __init__(self, *, pubsub_bus: pubsub.PubSub, player_: player.Player) -> None:
        """Initializer. Args: pubsub_bus: PubSub message bus. player_: Player."""
        <|body_0|>

    def _handle_play_status(self, status: player.PlayStatus) -> None:
        """Handler for PlayStatus updates."""
        <|body_1|>

    def on_slider_change_value(self, slider: Gtk.Scale, scroll: Gtk.ScrollType, value: float) -> bool:
        """Handler for the slider's change-value signal."""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        self._pubsub = pubsub_bus
        self._player = player_
        builder = Gtk.Builder.new_from_string(resources.read_text('pepper_music_player.ui', 'player_status_position_slider.glade'), length=-1)
        self.widget = builder.get_object('container')
        alignment.set_direction_recursive(self.widget, Gtk.TextDirection.LTR)
        self._position: Gtk.Label = builder.get_object('position')
        self._duration: Gtk.Label = builder.get_object('duration')
        self.slider: Gtk.Scale = builder.get_object('slider')
        self._pubsub.subscribe(player.PlayStatus, self._handle_play_status, want_last_message=True)
        builder.connect_signals(self)
<|end_body_0|>

<|body_start_1|>
        alignment.fill_aligned_numerical_label(self._position, formatting.format_timedelta(None if status.state is player.State.STOPPED else status.position))
        alignment.fill_aligned_numerical_label(self._duration, formatting.format_timedelta(None if status.state is player.State.STOPPED else status.duration))
        self.slider.set_range(0.0, status.duration.total_seconds())
        self.slider.set_value(status.position.total_seconds())
<|end_body_1|>

<|body_start_2|>
        del slider, scroll
        lower = self.slider.get_adjustment().get_lower()
        upper = self.slider.get_adjustment().get_upper()
        self._player.seek(datetime.timedelta(seconds=min(max(value, lower), upper)))
        return False
<|end_body_2|>

Solution:
class PositionSlider:
    """Position slider, including labels for the current position and duration. Attributes: widget: Widget containing the slider and labels. slider: Slider for seeking. This is public for use in tests only."""

    def __init__(self, *, pubsub_bus: pubsub.PubSub, player_: player.Player) -> None:
        """Initializer. Args: pubsub_bus: PubSub message bus. player_: Player."""
        self._pubsub = pubsub_bus
        self._player = player_
        builder = Gtk.Builder.new_from_string(resources.read_text('pepper_music_player.ui', 'player_status_position_slider.glade'), length=-1)
        self.widget = builder.get_object('container')
        alignment.set_direction_recursive(self.widget, Gtk.TextDirection.LTR)
        self._position: Gtk.Label = builder.get_object('position')
        self._duration: Gtk.Label = builder.get_object('duration')
        self.slider: Gtk.Scale = builder.get_object('slider')
        self._pubsub.subscribe(player.PlayStatus, self._handle_play_status, want_last_message=True)
        builder.connect_signals(self)

    def _handle_play_status(self, status: player.PlayStatus) -> None:
        """Handler for PlayStatus updates."""
        alignment.fill_aligned_numerical_label(self._position, formatting.format_timedelta(None if status.state is player.State.STOPPED else status.position))
        alignment.fill_aligned_numerical_label(self._duration, formatting.format_timedelta(None if status.state is player.State.STOPPED else status.duration))
        self.slider.set_range(0.0, status.duration.total_seconds())
        self.slider.set_value(status.position.total_seconds())

    def on_slider_change_value(self, slider: Gtk.Scale, scroll: Gtk.ScrollType, value: float) -> bool:
        """Handler for the slider's change-value signal."""
        del slider, scroll
        lower = self.slider.get_adjustment().get_lower()
        upper = self.slider.get_adjustment().get_upper()
        self._player.seek(datetime.timedelta(seconds=min(max(value, lower), upper)))
        return False


delete

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

Class description:
Resource for managing individual user permissions.

Method signatures and docstrings:
- def get(self, namespace_name, repository_name, username): Get the permission for the specified user.
- def put(self, namespace_name, repository_name, username): Update the perimssions for an existing repository.
- def delete(self, namespace_name, repository_name, username): Delete the permission for the user.

Implement the Python class `RepositoryUserPermission` described below.

Class description:
Resource for managing individual user permissions.

Method signatures and docstrings:
- def get(self, namespace_name, repository_name, username): Get the permission for the specified user.
- def put(self, namespace_name, repository_name, username): Update the perimssions for an existing repository.
- def delete(self, namespace_name, repository_name, username): Delete the permission for the user.

<|skeleton|>
class RepositoryUserPermission:
    """Resource for managing individual user permissions."""

    def get(self, namespace_name, repository_name, username):
        """Get the permission for the specified user."""
        <|body_0|>

    def put(self, namespace_name, repository_name, username):
        """Update the perimssions for an existing repository."""
        <|body_1|>

    def delete(self, namespace_name, repository_name, username):
        """Delete the permission for the user."""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        logger.debug('Get repo: %s/%s permissions for user %s', namespace_name, repository_name, username)
        perm = model.get_repo_permission_for_user(username, namespace_name, repository_name)
        return perm.to_dict()
<|end_body_0|>

<|body_start_1|>
        new_permission = request.get_json()
        logger.debug('Setting permission to: %s for user %s', new_permission['role'], username)
        try:
            perm = model.set_repo_permission_for_user(username, namespace_name, repository_name, new_permission['role'])
            resp = perm.to_dict()
        except SaveException as ex:
            raise request_error(exception=ex)
        log_action('change_repo_permission', namespace_name, {'username': username, 'repo': repository_name, 'namespace': namespace_name, 'role': new_permission['role']}, repo_name=repository_name)
        return (resp, 200)
<|end_body_1|>

<|body_start_2|>
        try:
            model.delete_repo_permission_for_user(username, namespace_name, repository_name)
        except DeleteException as ex:
            raise request_error(exception=ex)
        log_action('delete_repo_permission', namespace_name, {'username': username, 'repo': repository_name, 'namespace': namespace_name}, repo_name=repository_name)
        return ('', 204)
<|end_body_2|>

Solution:
class RepositoryUserPermission:
    """Resource for managing individual user permissions."""

    def get(self, namespace_name, repository_name, username):
        """Get the permission for the specified user."""
        logger.debug('Get repo: %s/%s permissions for user %s', namespace_name, repository_name, username)
        perm = model.get_repo_permission_for_user(username, namespace_name, repository_name)
        return perm.to_dict()

    def put(self, namespace_name, repository_name, username):
        """Update the perimssions for an existing repository."""
        new_permission = request.get_json()
        logger.debug('Setting permission to: %s for user %s', new_permission['role'], username)
        try:
            perm = model.set_repo_permission_for_user(username, namespace_name, repository_name, new_permission['role'])
            resp = perm.to_dict()
        except SaveException as ex:
            raise request_error(exception=ex)
        log_action('change_repo_permission', namespace_name, {'username': username, 'repo': repository_name, 'namespace': namespace_name, 'role': new_permission['role']}, repo_name=repository_name)
        return (resp, 200)

    def delete(self, namespace_name, repository_name, username):
        """Delete the permission for the user."""
        try:
            model.delete_repo_permission_for_user(username, namespace_name, repository_name)
        except DeleteException as ex:
            raise request_error(exception=ex)
        log_action('delete_repo_permission', namespace_name, {'username': username, 'repo': repository_name, 'namespace': namespace_name}, repo_name=repository_name)
        return ('', 204)


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

Class description:
This class represents the model of a Filter view. It defines the type of the packets to be shown, the subservice id and the submessage id

Method signatures and docstrings:
- def __init__(self): This is the constructor of the class
- def set_filter_options(self, type: str, subsvc: int, submsg: int): This method sets all the parameters :param type: The packet type :param subsvc: The packet subservice :param submsg: The packet submessage
- def get_filter_options(self): This method gets all the parameters of the filter :return: A dictionary with all the teh parameters of tge filter

Implement the Python class `FilterModel` described below.

Class description:
This class represents the model of a Filter view. It defines the type of the packets to be shown, the subservice id and the submessage id

Method signatures and docstrings:
- def __init__(self): This is the constructor of the class
- def set_filter_options(self, type: str, subsvc: int, submsg: int): This method sets all the parameters :param type: The packet type :param subsvc: The packet subservice :param submsg: The packet submessage
- def get_filter_options(self): This method gets all the parameters of the filter :return: A dictionary with all the teh parameters of tge filter

<|skeleton|>
class FilterModel:
    """This class represents the model of a Filter view. It defines the type of the packets to be shown, the subservice id and the submessage id"""

    def __init__(self):
        """This is the constructor of the class"""
        <|body_0|>

    def set_filter_options(self, type: str, subsvc: int, submsg: int):
        """This method sets all the parameters :param type: The packet type :param subsvc: The packet subservice :param submsg: The packet submessage"""
        <|body_1|>

    def get_filter_options(self):
        """This method gets all the parameters of the filter :return: A dictionary with all the teh parameters of tge filter"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        self.type = None
        self.subsvc = None
        self.submsg = None
<|end_body_0|>

<|body_start_1|>
        self.type = type
        self.subsvc = subsvc
        self.submsg = submsg
<|end_body_1|>

<|body_start_2|>
        if self.type == '' and self.subsvc == 0 and (self.submsg == 0):
            return None
        filtr = {'type': self.type, 'svc': self.subsvc, 'msg': self.submsg}
        print(filtr)
        return filtr
<|end_body_2|>

Solution:
class FilterModel:
    """This class represents the model of a Filter view. It defines the type of the packets to be shown, the subservice id and the submessage id"""

    def __init__(self):
        """This is the constructor of the class"""
        self.type = None
        self.subsvc = None
        self.submsg = None

    def set_filter_options(self, type: str, subsvc: int, submsg: int):
        """This method sets all the parameters :param type: The packet type :param subsvc: The packet subservice :param submsg: The packet submessage"""
        self.type = type
        self.subsvc = subsvc
        self.submsg = submsg

    def get_filter_options(self):
        """This method gets all the parameters of the filter :return: A dictionary with all the teh parameters of tge filter"""
        if self.type == '' and self.subsvc == 0 and (self.submsg == 0):
            return None
        filtr = {'type': self.type, 'svc': self.subsvc, 'msg': self.submsg}
        print(filtr)
        return filtr


set

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

Class description:
LRU style cache.

Method signatures and docstrings:
- def __init__(self, size=10, label='cache'): LRU style cache Args: size (int, optional): maximum number of elements in the cache. Defaults to 10. label (str, optional): A label an instance of the cache. Defaults to "cache".
- def get(self, key): Return the cached value associated with the input key. The key:value combination are moved to top of the cache. Args: key (hashable): identifier for cached object Returns: (any): Cached object associated with the input key or None
- def set(self, key, value): Store the input value in the cache. The cache contents of the cache are adjusted if the size limit is exceeded. Args: key (hashable): identifier for cached object value (any): value to be cached Returns: bool: True for success or false otherwise

Implement the Python class `CacheUtils` described below.

Class description:
LRU style cache.

Method signatures and docstrings:
- def __init__(self, size=10, label='cache'): LRU style cache Args: size (int, optional): maximum number of elements in the cache. Defaults to 10. label (str, optional): A label an instance of the cache. Defaults to "cache".
- def get(self, key): Return the cached value associated with the input key. The key:value combination are moved to top of the cache. Args: key (hashable): identifier for cached object Returns: (any): Cached object associated with the input key or None
- def set(self, key, value): Store the input value in the cache. The cache contents of the cache are adjusted if the size limit is exceeded. Args: key (hashable): identifier for cached object value (any): value to be cached Returns: bool: True for success or false otherwise

<|skeleton|>
class CacheUtils:
    """LRU style cache."""

    def __init__(self, size=10, label='cache'):
        """LRU style cache Args: size (int, optional): maximum number of elements in the cache. Defaults to 10. label (str, optional): A label an instance of the cache. Defaults to "cache"."""
        <|body_0|>

    def get(self, key):
        """Return the cached value associated with the input key. The key:value combination are moved to top of the cache. Args: key (hashable): identifier for cached object Returns: (any): Cached object associated with the input key or None"""
        <|body_1|>

    def set(self, key, value):
        """Store the input value in the cache. The cache contents of the cache are adjusted if the size limit is exceeded. Args: key (hashable): identifier for cached object value (any): value to be cached Returns: bool: True for success or false otherwise"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        self.__size = size
        self.__cache = OrderedDict()
        self.__label = label
<|end_body_0|>

<|body_start_1|>
        try:
            value = self.__cache.pop(key)
            self.__cache[key] = value
            return value
        except KeyError:
            return None
<|end_body_1|>

<|body_start_2|>
        try:
            try:
                self.__cache.pop(key)
            except KeyError:
                if len(self.__cache) >= self.__size:
                    self.__cache.popitem(last=False)
            self.__cache[key] = value
            return True
        except Exception as e:
            logger.exception('Failing for %s with %s', self.__label, str(e))
        return False
<|end_body_2|>

Solution:
class CacheUtils:
    """LRU style cache."""

    def __init__(self, size=10, label='cache'):
        """LRU style cache Args: size (int, optional): maximum number of elements in the cache. Defaults to 10. label (str, optional): A label an instance of the cache. Defaults to "cache"."""
        self.__size = size
        self.__cache = OrderedDict()
        self.__label = label

    def get(self, key):
        """Return the cached value associated with the input key. The key:value combination are moved to top of the cache. Args: key (hashable): identifier for cached object Returns: (any): Cached object associated with the input key or None"""
        try:
            value = self.__cache.pop(key)
            self.__cache[key] = value
            return value
        except KeyError:
            return None

    def set(self, key, value):
        """Store the input value in the cache. The cache contents of the cache are adjusted if the size limit is exceeded. Args: key (hashable): identifier for cached object value (any): value to be cached Returns: bool: True for success or false otherwise"""
        try:
            try:
                self.__cache.pop(key)
            except KeyError:
                if len(self.__cache) >= self.__size:
                    self.__cache.popitem(last=False)
            self.__cache[key] = value
            return True
        except Exception as e:
            logger.exception('Failing for %s with %s', self.__label, str(e))
        return False


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

Class description:
**Loads and provides access to implicit price deflators by calendar year.**

Method signatures and docstrings:
- def get_price_deflator(calendar_year): Get the implicit price deflator for the given calendar year. Args: calendar_year (int): the calendar year to get the function for Returns: The implicit price deflator for the given calendar year.
- def dollar_adjustment_factor(dollar_basis_input): Args: dollar_basis_input (int): the dollar basis of the input value. Returns: The multiplicative factor that can be applied to a cost in dollar_basis_input to express that value in analysis_dollar_basis.
- def init_from_file(filename, verbose=False): Initialize class data from input file. Args: filename (str): name of input file verbose (bool): enable additional console and logfile output if True Returns: List of template/input errors, else empty list on success

Implement the Python class `ImplicitPriceDeflators` described below.

Class description:
**Loads and provides access to implicit price deflators by calendar year.**

Method signatures and docstrings:
- def get_price_deflator(calendar_year): Get the implicit price deflator for the given calendar year. Args: calendar_year (int): the calendar year to get the function for Returns: The implicit price deflator for the given calendar year.
- def dollar_adjustment_factor(dollar_basis_input): Args: dollar_basis_input (int): the dollar basis of the input value. Returns: The multiplicative factor that can be applied to a cost in dollar_basis_input to express that value in analysis_dollar_basis.
- def init_from_file(filename, verbose=False): Initialize class data from input file. Args: filename (str): name of input file verbose (bool): enable additional console and logfile output if True Returns: List of template/input errors, else empty list on success

<|skeleton|>
class ImplicitPriceDeflators:
    """**Loads and provides access to implicit price deflators by calendar year.**"""

    def get_price_deflator(calendar_year):
        """Get the implicit price deflator for the given calendar year. Args: calendar_year (int): the calendar year to get the function for Returns: The implicit price deflator for the given calendar year."""
        <|body_0|>

    def dollar_adjustment_factor(dollar_basis_input):
        """Args: dollar_basis_input (int): the dollar basis of the input value. Returns: The multiplicative factor that can be applied to a cost in dollar_basis_input to express that value in analysis_dollar_basis."""
        <|body_1|>

    def init_from_file(filename, verbose=False):
        """Initialize class data from input file. Args: filename (str): name of input file verbose (bool): enable additional console and logfile output if True Returns: List of template/input errors, else empty list on success"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        cache_key = calendar_year
        if cache_key not in ImplicitPriceDeflators._cache:
            calendar_years = pd.Series(ImplicitPriceDeflators._data.keys())
            if len(calendar_years[calendar_years <= calendar_year]) > 0:
                year = max(calendar_years[calendar_years <= calendar_year])
                ImplicitPriceDeflators._cache[cache_key] = ImplicitPriceDeflators._data[year]['price_deflator']
            else:
                raise Exception(f'Missing implicit price deflator for {calendar_year} or prior')
            if max(calendar_years[calendar_years <= calendar_year]) < calendar_year:
                raise Exception(f'Missing implicit price deflator for {calendar_year}')
        return ImplicitPriceDeflators._cache[cache_key]
<|end_body_0|>

<|body_start_1|>
        analysis_basis = omega_globals.options.analysis_dollar_basis
        adj_factor_numerator = ImplicitPriceDeflators.get_price_deflator(analysis_basis)
        adj_factor_denominator = ImplicitPriceDeflators.get_price_deflator(dollar_basis_input)
        adj_factor = adj_factor_numerator / adj_factor_denominator
        return adj_factor
<|end_body_1|>

<|body_start_2|>
        ImplicitPriceDeflators._data.clear()
        ImplicitPriceDeflators._cache.clear()
        if verbose:
            omega_log.logwrite('\nInitializing data from %s...' % filename)
        input_template_name = 'context_implicit_price_deflators'
        input_template_version = 0.22
        input_template_columns = {'calendar_year', 'price_deflator'}
        template_errors = validate_template_version_info(filename, input_template_name, input_template_version, verbose=verbose)
        if not template_errors:
            df = pd.read_csv(filename, skiprows=1)
            template_errors = validate_template_column_names(filename, input_template_columns, df.columns, verbose=verbose)
            if not template_errors:
                ImplicitPriceDeflators._data = df.set_index('calendar_year').to_dict(orient='index')
        return template_errors
<|end_body_2|>

Solution:
class ImplicitPriceDeflators:
    """**Loads and provides access to implicit price deflators by calendar year.**"""

    def get_price_deflator(calendar_year):
        """Get the implicit price deflator for the given calendar year. Args: calendar_year (int): the calendar year to get the function for Returns: The implicit price deflator for the given calendar year."""
        cache_key = calendar_year
        if cache_key not in ImplicitPriceDeflators._cache:
            calendar_years = pd.Series(ImplicitPriceDeflators._data.keys())
            if len(calendar_years[calendar_years <= calendar_year]) > 0:
                year = max(calendar_years[calendar_years <= calendar_year])
                ImplicitPriceDeflators._cache[cache_key] = ImplicitPriceDeflators._data[year]['price_deflator']
            else:
                raise Exception(f'Missing implicit price deflator for {calendar_year} or prior')
            if max(calendar_years[calendar_years <= calendar_year]) < calendar_year:
                raise Exception(f'Missing implicit price deflator for {calendar_year}')
        return ImplicitPriceDeflators._cache[cache_key]

    def dollar_adjustment_factor(dollar_basis_input):
        """Args: dollar_basis_input (int): the dollar basis of the input value. Returns: The multiplicative factor that can be applied to a cost in dollar_basis_input to express that value in analysis_dollar_basis."""
        analysis_basis = omega_globals.options.analysis_dollar_basis
        adj_factor_numerator = ImplicitPriceDeflators.get_price_deflator(analysis_basis)
        adj_factor_denominator = ImplicitPriceDeflators.get_price_deflator(dollar_basis_input)
        adj_factor = adj_factor_numerator / adj_factor_denominator
        return adj_factor

    def init_from_file(filename, verbose=False):
        """Initialize class data from input file. Args: filename (str): name of input file verbose (bool): enable additional console and logfile output if True Returns: List of template/input errors, else empty list on success"""
        ImplicitPriceDeflators._data.clear()
        ImplicitPriceDeflators._cache.clear()
        if verbose:
            omega_log.logwrite('\nInitializing data from %s...' % filename)
        input_template_name = 'context_implicit_price_deflators'
        input_template_version = 0.22
        input_template_columns = {'calendar_year', 'price_deflator'}
        template_errors = validate_template_version_info(filename, input_template_name, input_template_version, verbose=verbose)
        if not template_errors:
            df = pd.read_csv(filename, skiprows=1)
            template_errors = validate_template_column_names(filename, input_template_columns, df.columns, verbose=verbose)
            if not template_errors:
                ImplicitPriceDeflators._data = df.set_index('calendar_year').to_dict(orient='index')
        return template_errors


forward

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

Class description:
Class implementing the Information Maximization Generative Adversarial Networks. References ---------- `Paper <https://arxiv.org/abs/1606.03657>`_ Warnings -------- This Network is designed for training only; if you want to predict from an already trained network, it might be best, to split this network into its parts (i. e. separating the discriminator from the generator). This will give a significant boost in inference speed and a significant decrease in memory consumption, since no memory is allocated for additional weights of the unused parts and no inference is done for them. If this whole network is used, inferences might be done multiple times per network, to obtain all necessary (int

Method signatures and docstrings:
- def __init__(self, latent_dim, n_classes, code_dim, img_size, num_channels, lambda_cat=1.0, lambda_cont=0.1, generator_cls=Generator, discriminator_cls=Discriminator): Parameters ---------- latent_dim : int the size of the latent dimension n_classes : int the number of classes code_dim : int the size of the code dimension img_size : int the number of pixels per image side num_channels : int number of image channels lambda_cat : float weighting factor specifying the impact of the categorical loss onto the info-loss lambda_cont : float weighting factor specifying the impact of the continuous loss onto the info loss generator_cls : class implementing the actual generator topology discriminator_cls : class implementing the actual discriminator topology
- def forward(self, imgs, labels=None, z=None, code=None): Forwards a single set of batches through the network Parameters ---------- imgs : :class:`torch.Tensor` the image batch labels : :class:`torch.Tensor` the labels batch, will be sampled if not given z : :class:`torch.Tensor` the noise batch, will be sampled if not given code : :class:`torch.Tensor` the code batch, will be sampled if not given Returns ------- dict a dictionary containing all (intermediate) results for loss calculation and training

Implement the Python class `InfoGAN` described below.

Class description:
Class implementing the Information Maximization Generative Adversarial Networks. References ---------- `Paper <https://arxiv.org/abs/1606.03657>`_ Warnings -------- This Network is designed for training only; if you want to predict from an already trained network, it might be best, to split this network into its parts (i. e. separating the discriminator from the generator). This will give a significant boost in inference speed and a significant decrease in memory consumption, since no memory is allocated for additional weights of the unused parts and no inference is done for them. If this whole network is used, inferences might be done multiple times per network, to obtain all necessary (int

Method signatures and docstrings:
- def __init__(self, latent_dim, n_classes, code_dim, img_size, num_channels, lambda_cat=1.0, lambda_cont=0.1, generator_cls=Generator, discriminator_cls=Discriminator): Parameters ---------- latent_dim : int the size of the latent dimension n_classes : int the number of classes code_dim : int the size of the code dimension img_size : int the number of pixels per image side num_channels : int number of image channels lambda_cat : float weighting factor specifying the impact of the categorical loss onto the info-loss lambda_cont : float weighting factor specifying the impact of the continuous loss onto the info loss generator_cls : class implementing the actual generator topology discriminator_cls : class implementing the actual discriminator topology
- def forward(self, imgs, labels=None, z=None, code=None): Forwards a single set of batches through the network Parameters ---------- imgs : :class:`torch.Tensor` the image batch labels : :class:`torch.Tensor` the labels batch, will be sampled if not given z : :class:`torch.Tensor` the noise batch, will be sampled if not given code : :class:`torch.Tensor` the code batch, will be sampled if not given Returns ------- dict a dictionary containing all (intermediate) results for loss calculation and training

<|skeleton|>
class InfoGAN:
    """Class implementing the Information Maximization Generative Adversarial Networks. References ---------- `Paper <https://arxiv.org/abs/1606.03657>`_ Warnings -------- This Network is designed for training only; if you want to predict from an already trained network, it might be best, to split this network into its parts (i. e. separating the discriminator from the generator). This will give a significant boost in inference speed and a significant decrease in memory consumption, since no memory is allocated for additional weights of the unused parts and no inference is done for them. If this whole network is used, inferences might be done multiple times per network, to obtain all necessary (int"""

    def __init__(self, latent_dim, n_classes, code_dim, img_size, num_channels, lambda_cat=1.0, lambda_cont=0.1, generator_cls=Generator, discriminator_cls=Discriminator):
        """Parameters ---------- latent_dim : int the size of the latent dimension n_classes : int the number of classes code_dim : int the size of the code dimension img_size : int the number of pixels per image side num_channels : int number of image channels lambda_cat : float weighting factor specifying the impact of the categorical loss onto the info-loss lambda_cont : float weighting factor specifying the impact of the continuous loss onto the info loss generator_cls : class implementing the actual generator topology discriminator_cls : class implementing the actual discriminator topology"""
        <|body_0|>

    def forward(self, imgs, labels=None, z=None, code=None):
        """Forwards a single set of batches through the network Parameters ---------- imgs : :class:`torch.Tensor` the image batch labels : :class:`torch.Tensor` the labels batch, will be sampled if not given z : :class:`torch.Tensor` the noise batch, will be sampled if not given code : :class:`torch.Tensor` the code batch, will be sampled if not given Returns ------- dict a dictionary containing all (intermediate) results for loss calculation and training"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        super().__init__()
        self.generator = generator_cls(latent_dim, n_classes, code_dim, img_size, num_channels)
        self.discriminator = discriminator_cls(code_dim, n_classes, num_channels, img_size)
        self._n_classes = n_classes
        self._latent_dim = latent_dim
        self._code_dim = code_dim
        self.lambda_cat = lambda_cat
        self.lambda_cont = lambda_cont
        self.generator.apply(weights_init_normal)
        self.discriminator.apply(weights_init_normal)
<|end_body_0|>

<|body_start_1|>
        if z is None:
            z = torch.randn(imgs.size(0), self._latent_dim, device=imgs.device, dtype=imgs.dtype)
        if labels is None:
            labels = torch.randint(self._n_classes, (imgs.size(0), 1), device=imgs.device, dtype=torch.long)
        if labels.size(-1) != self._n_classes:
            labels = one_hot_batch(labels.unsqueeze(1), num_classes=self._n_classes)
        if code is None:
            code = torch.empty(imgs.size(0), self._code_dim, device=imgs.device, dtype=imgs.dtype)
            code.uniform_(-1, 1)
        gen_imgs = self.generator(z, labels, code)
        validity_real, _, _ = self.discriminator(imgs)
        validity_fake, labels_fake, code_fake = self.discriminator(gen_imgs)
        return {'validity_real': validity_real, 'validity_fake': validity_fake, 'labels_real': labels, 'labels_fake': labels_fake, 'code_real': code, 'code_fake': code_fake, 'gen_imgs': gen_imgs}
<|end_body_1|>

Solution:
class InfoGAN:
    """Class implementing the Information Maximization Generative Adversarial Networks. References ---------- `Paper <https://arxiv.org/abs/1606.03657>`_ Warnings -------- This Network is designed for training only; if you want to predict from an already trained network, it might be best, to split this network into its parts (i. e. separating the discriminator from the generator). This will give a significant boost in inference speed and a significant decrease in memory consumption, since no memory is allocated for additional weights of the unused parts and no inference is done for them. If this whole network is used, inferences might be done multiple times per network, to obtain all necessary (int"""

    def __init__(self, latent_dim, n_classes, code_dim, img_size, num_channels, lambda_cat=1.0, lambda_cont=0.1, generator_cls=Generator, discriminator_cls=Discriminator):
        """Parameters ---------- latent_dim : int the size of the latent dimension n_classes : int the number of classes code_dim : int the size of the code dimension img_size : int the number of pixels per image side num_channels : int number of image channels lambda_cat : float weighting factor specifying the impact of the categorical loss onto the info-loss lambda_cont : float weighting factor specifying the impact of the continuous loss onto the info loss generator_cls : class implementing the actual generator topology discriminator_cls : class implementing the actual discriminator topology"""
        super().__init__()
        self.generator = generator_cls(latent_dim, n_classes, code_dim, img_size, num_channels)
        self.discriminator = discriminator_cls(code_dim, n_classes, num_channels, img_size)
        self._n_classes = n_classes
        self._latent_dim = latent_dim
        self._code_dim = code_dim
        self.lambda_cat = lambda_cat
        self.lambda_cont = lambda_cont
        self.generator.apply(weights_init_normal)
        self.discriminator.apply(weights_init_normal)

    def forward(self, imgs, labels=None, z=None, code=None):
        """Forwards a single set of batches through the network Parameters ---------- imgs : :class:`torch.Tensor` the image batch labels : :class:`torch.Tensor` the labels batch, will be sampled if not given z : :class:`torch.Tensor` the noise batch, will be sampled if not given code : :class:`torch.Tensor` the code batch, will be sampled if not given Returns ------- dict a dictionary containing all (intermediate) results for loss calculation and training"""
        if z is None:
            z = torch.randn(imgs.size(0), self._latent_dim, device=imgs.device, dtype=imgs.dtype)
        if labels is None:
            labels = torch.randint(self._n_classes, (imgs.size(0), 1), device=imgs.device, dtype=torch.long)
        if labels.size(-1) != self._n_classes:
            labels = one_hot_batch(labels.unsqueeze(1), num_classes=self._n_classes)
        if code is None:
            code = torch.empty(imgs.size(0), self._code_dim, device=imgs.device, dtype=imgs.dtype)
            code.uniform_(-1, 1)
        gen_imgs = self.generator(z, labels, code)
        validity_real, _, _ = self.discriminator(imgs)
        validity_fake, labels_fake, code_fake = self.discriminator(gen_imgs)
        return {'validity_real': validity_real, 'validity_fake': validity_fake, 'labels_real': labels, 'labels_fake': labels_fake, 'code_real': code, 'code_fake': code_fake, 'gen_imgs': gen_imgs}