cleanup

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

Class description:
Configure boot device to bios, pxe, hdd, cdrom, floppy in persistent mode when boot device created using cimc config and booted from it

Method signatures and docstrings:
- def setup(self, cimc_util_obj): Test Case Setup
- def test(self, cimc_util_obj, config, parameter): ipmi command to set boot to bios, pxe, hdd, cdrom, floppy drive options in persistent mode when cimc config set and booted from it
- def cleanup(self, cimc_util_obj, config): Test Case Cleanup

Implement the Python class `CimcConfigIPMICmdPersistentBootDevice` described below.

Class description:
Configure boot device to bios, pxe, hdd, cdrom, floppy in persistent mode when boot device created using cimc config and booted from it

Method signatures and docstrings:
- def setup(self, cimc_util_obj): Test Case Setup
- def test(self, cimc_util_obj, config, parameter): ipmi command to set boot to bios, pxe, hdd, cdrom, floppy drive options in persistent mode when cimc config set and booted from it
- def cleanup(self, cimc_util_obj, config): Test Case Cleanup

<|skeleton|>
class CimcConfigIPMICmdPersistentBootDevice:
    """Configure boot device to bios, pxe, hdd, cdrom, floppy in persistent mode when boot device created using cimc config and booted from it"""

    def setup(self, cimc_util_obj):
        """Test Case Setup"""
        <|body_0|>

    def test(self, cimc_util_obj, config, parameter):
        """ipmi command to set boot to bios, pxe, hdd, cdrom, floppy drive options in persistent mode when cimc config set and booted from it"""
        <|body_1|>

    def cleanup(self, cimc_util_obj, config):
        """Test Case Cleanup"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        log.info('Setup Section verifyProcessorDetails')
        host_ip = classparam['host_ip']
        boot_order_obj = classparam['boot_order_obj']
        self.host_serial_handle = classparam['host_serial_handle']
        self.host_serial_handle.connect_to_host_serial()
        log.info('Create boot device from CIMC config and boot from it')
        if boot_order_obj.create_and_config_localhdd_boot_device('HDD') is False:
            self.failed('Failed to create boot device from CIMC')
        log.info('Waiting for host to boot into respective boot device')
        cimc_util_obj.power_cycle_host()
        res = cimc_util_obj.verify_host_up(hostname=host_ip, wait_for_ping_fail=False)
        if res is False:
            self.failed('Failed to boot from cimc configured boot device')
        else:
            log.info('Successfully booted from cimc configured boot device')
<|end_body_0|>

<|body_start_1|>
        expected_out = classparam['expected_out']
        validation_string = classparam['validation_string']
        bootdev = parameter
        options = 'persistent'
        cmd_out = configure_boot_device_ipmi(config, bootdev, options)
        if cmd_out == expected_out + bootdev:
            log.info('Successfully executed, and got expected output: ' + str(cmd_out))
        else:
            log.error('Failed to get expected command output. Expected was %s, but got as %s' % (expected_out + bootdev, cmd_out))
        log.info('Validation: connecting host over telnet and verify console logs')
        log.info('1st Host reboot: Verify that host boots to expected boot device %s' % parameter)
        cimc_util_obj.power_cycle_host()
        cmd = validation_string[parameter]
        log.info('Expected string is: ' + str(cmd.encode()))
        result = self.host_serial_handle.validate_host_console_output(exp_string=cmd.encode())
        if result == 'Fail':
            self.failed('Failed to validate persistent boot for boot device %s' % parameter)
        log.info('2nd Host Reboot: Verify that host boots again to previously booted boot device %s' % parameter)
        cimc_util_obj.power_cycle_host()
        cmd = validation_string[parameter]
        log.info('Expected string is: ' + str(cmd.encode()))
        result2 = self.host_serial_handle.validate_host_console_output(exp_string=cmd.encode())
        if result2 == 'Fail':
            self.failed('Failed to validate persistent boot for boot device %s' % parameter)
        self.passed('Successfully validated persistent ipmi boot for boot device %s' % parameter)
<|end_body_1|>

<|body_start_2|>
        self.host_serial_handle.disconnect()
        remove_consistent_ipmi_boot(cimc_util_obj, config)
        log.info('Cleanup section passed')
<|end_body_2|>

Solution:
class CimcConfigIPMICmdPersistentBootDevice:
    """Configure boot device to bios, pxe, hdd, cdrom, floppy in persistent mode when boot device created using cimc config and booted from it"""

    def setup(self, cimc_util_obj):
        """Test Case Setup"""
        log.info('Setup Section verifyProcessorDetails')
        host_ip = classparam['host_ip']
        boot_order_obj = classparam['boot_order_obj']
        self.host_serial_handle = classparam['host_serial_handle']
        self.host_serial_handle.connect_to_host_serial()
        log.info('Create boot device from CIMC config and boot from it')
        if boot_order_obj.create_and_config_localhdd_boot_device('HDD') is False:
            self.failed('Failed to create boot device from CIMC')
        log.info('Waiting for host to boot into respective boot device')
        cimc_util_obj.power_cycle_host()
        res = cimc_util_obj.verify_host_up(hostname=host_ip, wait_for_ping_fail=False)
        if res is False:
            self.failed('Failed to boot from cimc configured boot device')
        else:
            log.info('Successfully booted from cimc configured boot device')

    def test(self, cimc_util_obj, config, parameter):
        """ipmi command to set boot to bios, pxe, hdd, cdrom, floppy drive options in persistent mode when cimc config set and booted from it"""
        expected_out = classparam['expected_out']
        validation_string = classparam['validation_string']
        bootdev = parameter
        options = 'persistent'
        cmd_out = configure_boot_device_ipmi(config, bootdev, options)
        if cmd_out == expected_out + bootdev:
            log.info('Successfully executed, and got expected output: ' + str(cmd_out))
        else:
            log.error('Failed to get expected command output. Expected was %s, but got as %s' % (expected_out + bootdev, cmd_out))
        log.info('Validation: connecting host over telnet and verify console logs')
        log.info('1st Host reboot: Verify that host boots to expected boot device %s' % parameter)
        cimc_util_obj.power_cycle_host()
        cmd = validation_string[parameter]
        log.info('Expected string is: ' + str(cmd.encode()))
        result = self.host_serial_handle.validate_host_console_output(exp_string=cmd.encode())
        if result == 'Fail':
            self.failed('Failed to validate persistent boot for boot device %s' % parameter)
        log.info('2nd Host Reboot: Verify that host boots again to previously booted boot device %s' % parameter)
        cimc_util_obj.power_cycle_host()
        cmd = validation_string[parameter]
        log.info('Expected string is: ' + str(cmd.encode()))
        result2 = self.host_serial_handle.validate_host_console_output(exp_string=cmd.encode())
        if result2 == 'Fail':
            self.failed('Failed to validate persistent boot for boot device %s' % parameter)
        self.passed('Successfully validated persistent ipmi boot for boot device %s' % parameter)

    def cleanup(self, cimc_util_obj, config):
        """Test Case Cleanup"""
        self.host_serial_handle.disconnect()
        remove_consistent_ipmi_boot(cimc_util_obj, config)
        log.info('Cleanup section passed')


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

Class description:
Prints output from PETSc's KSP solvers. Callable object given to KSP as a callback for printing the residual. Attributes ---------- _solver : _solver the openmdao solver. _norm : float the current norm. _norm0 : float the norm for the first iteration.

Method signatures and docstrings:
- def __init__(self, solver): Store pointer to the openmdao solver and initialize norms. Parameters ---------- solver : object the openmdao solver.
- def __call__(self, ksp, counter, norm): Store norm if first iteration, and print norm. Parameters ---------- ksp : object the KSP solver. counter : int the counter. norm : float the norm.

Implement the Python class `Monitor` described below.

Class description:
Prints output from PETSc's KSP solvers. Callable object given to KSP as a callback for printing the residual. Attributes ---------- _solver : _solver the openmdao solver. _norm : float the current norm. _norm0 : float the norm for the first iteration.

Method signatures and docstrings:
- def __init__(self, solver): Store pointer to the openmdao solver and initialize norms. Parameters ---------- solver : object the openmdao solver.
- def __call__(self, ksp, counter, norm): Store norm if first iteration, and print norm. Parameters ---------- ksp : object the KSP solver. counter : int the counter. norm : float the norm.

<|skeleton|>
class Monitor:
    """Prints output from PETSc's KSP solvers. Callable object given to KSP as a callback for printing the residual. Attributes ---------- _solver : _solver the openmdao solver. _norm : float the current norm. _norm0 : float the norm for the first iteration."""

    def __init__(self, solver):
        """Store pointer to the openmdao solver and initialize norms. Parameters ---------- solver : object the openmdao solver."""
        <|body_0|>

    def __call__(self, ksp, counter, norm):
        """Store norm if first iteration, and print norm. Parameters ---------- ksp : object the KSP solver. counter : int the counter. norm : float the norm."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self._solver = solver
        self._norm = 1.0
        self._norm0 = 1.0
<|end_body_0|>

<|body_start_1|>
        if counter == 0 and norm != 0.0:
            self._norm0 = norm
        self._norm = norm
        self._solver._mpi_print(counter, norm, norm / self._norm0)
        self._solver._iter_count += 1
<|end_body_1|>

Solution:
class Monitor:
    """Prints output from PETSc's KSP solvers. Callable object given to KSP as a callback for printing the residual. Attributes ---------- _solver : _solver the openmdao solver. _norm : float the current norm. _norm0 : float the norm for the first iteration."""

    def __init__(self, solver):
        """Store pointer to the openmdao solver and initialize norms. Parameters ---------- solver : object the openmdao solver."""
        self._solver = solver
        self._norm = 1.0
        self._norm0 = 1.0

    def __call__(self, ksp, counter, norm):
        """Store norm if first iteration, and print norm. Parameters ---------- ksp : object the KSP solver. counter : int the counter. norm : float the norm."""
        if counter == 0 and norm != 0.0:
            self._norm0 = norm
        self._norm = norm
        self._solver._mpi_print(counter, norm, norm / self._norm0)
        self._solver._iter_count += 1


forward

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

Class description:
A class representing a mesh pooling layer. It supposes the input mesh is trivially poolable Attributes ---------- cached : bool if True caches the pooling data, otherwise computes it at every input index : LongTensor the vertices indices face : LongTensor the topology tensor Methods ------- forward(x, *args) pools the input data

Method signatures and docstrings:
- def __init__(self, index=None, face=None, cached=True): Parameters ---------- index : LongTensor (optional) the vertices indices (default is None) face : LongTensor (optional) the topology tensor (default is None) cached : bool (optional) if True caches the pooling data, otherwise computes it at every input (default is True)
- def forward(self, x, *args): Pools the input data Parameters ---------- x : Data the input mesh with N vertices args : Tensor... optional (N,D,) tensors Returns ------- Data or (Data, Tensor...) the pooled mesh and the other input data

Implement the Python class `MeshPooling` described below.

Class description:
A class representing a mesh pooling layer. It supposes the input mesh is trivially poolable Attributes ---------- cached : bool if True caches the pooling data, otherwise computes it at every input index : LongTensor the vertices indices face : LongTensor the topology tensor Methods ------- forward(x, *args) pools the input data

Method signatures and docstrings:
- def __init__(self, index=None, face=None, cached=True): Parameters ---------- index : LongTensor (optional) the vertices indices (default is None) face : LongTensor (optional) the topology tensor (default is None) cached : bool (optional) if True caches the pooling data, otherwise computes it at every input (default is True)
- def forward(self, x, *args): Pools the input data Parameters ---------- x : Data the input mesh with N vertices args : Tensor... optional (N,D,) tensors Returns ------- Data or (Data, Tensor...) the pooled mesh and the other input data

<|skeleton|>
class MeshPooling:
    """A class representing a mesh pooling layer. It supposes the input mesh is trivially poolable Attributes ---------- cached : bool if True caches the pooling data, otherwise computes it at every input index : LongTensor the vertices indices face : LongTensor the topology tensor Methods ------- forward(x, *args) pools the input data"""

    def __init__(self, index=None, face=None, cached=True):
        """Parameters ---------- index : LongTensor (optional) the vertices indices (default is None) face : LongTensor (optional) the topology tensor (default is None) cached : bool (optional) if True caches the pooling data, otherwise computes it at every input (default is True)"""
        <|body_0|>

    def forward(self, x, *args):
        """Pools the input data Parameters ---------- x : Data the input mesh with N vertices args : Tensor... optional (N,D,) tensors Returns ------- Data or (Data, Tensor...) the pooled mesh and the other input data"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        super(MeshPooling, self).__init__()
        self.cached = cached
        self.index = index
        self.face = face
<|end_body_0|>

<|body_start_1|>
        if self.matrix is None or not self.cached:
            self.face, self.index = unsubdivide(x.pos, x.face)[1:]
        x.pos = x.pos[self.index]
        x.norm = x.norm[self.index]
        x.face = self.face
        if len(args) == 0:
            return x
        return (x,) + tuple([a[self.index] for a in args])
<|end_body_1|>

Solution:
class MeshPooling:
    """A class representing a mesh pooling layer. It supposes the input mesh is trivially poolable Attributes ---------- cached : bool if True caches the pooling data, otherwise computes it at every input index : LongTensor the vertices indices face : LongTensor the topology tensor Methods ------- forward(x, *args) pools the input data"""

    def __init__(self, index=None, face=None, cached=True):
        """Parameters ---------- index : LongTensor (optional) the vertices indices (default is None) face : LongTensor (optional) the topology tensor (default is None) cached : bool (optional) if True caches the pooling data, otherwise computes it at every input (default is True)"""
        super(MeshPooling, self).__init__()
        self.cached = cached
        self.index = index
        self.face = face

    def forward(self, x, *args):
        """Pools the input data Parameters ---------- x : Data the input mesh with N vertices args : Tensor... optional (N,D,) tensors Returns ------- Data or (Data, Tensor...) the pooled mesh and the other input data"""
        if self.matrix is None or not self.cached:
            self.face, self.index = unsubdivide(x.pos, x.face)[1:]
        x.pos = x.pos[self.index]
        x.norm = x.norm[self.index]
        x.face = self.face
        if len(args) == 0:
            return x
        return (x,) + tuple([a[self.index] for a in args])


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

Class description:
Class -- PlayingCard Represents a playing card. Attributes: value -- the card's value, an integer. suit -- the card's suit, a string

Method signatures and docstrings:
- def __init__(self, value, suit): Constructor -- creates a new instance of PlayingCard Parameters: self -- the current PlayingCard object value -- the card's value, an integer suit -- the card's suit, a string
- def set_name(self): Method -- set_name Helper method to set the name of special cards. Parameter: self -- The current PlayingCard object Returns: Nothing. Sets the name attribute if applicable.
- def __str__(self): Method -- __str__ Creates a string representation of the PlayingCard Parameter: self -- The current PlayingCard object Returns: A string representation of the PlayingCard.
- def __eq__(self, other): Method -- __eq__ Checks if two objects are equal Parameters: self -- The current PlayingCard object other -- An object to compare self to. Returns: True if the two objects are equal, False otherwise.

Implement the Python class `PlayingCard` described below.

Class description:
Class -- PlayingCard Represents a playing card. Attributes: value -- the card's value, an integer. suit -- the card's suit, a string

Method signatures and docstrings:
- def __init__(self, value, suit): Constructor -- creates a new instance of PlayingCard Parameters: self -- the current PlayingCard object value -- the card's value, an integer suit -- the card's suit, a string
- def set_name(self): Method -- set_name Helper method to set the name of special cards. Parameter: self -- The current PlayingCard object Returns: Nothing. Sets the name attribute if applicable.
- def __str__(self): Method -- __str__ Creates a string representation of the PlayingCard Parameter: self -- The current PlayingCard object Returns: A string representation of the PlayingCard.
- def __eq__(self, other): Method -- __eq__ Checks if two objects are equal Parameters: self -- The current PlayingCard object other -- An object to compare self to. Returns: True if the two objects are equal, False otherwise.

<|skeleton|>
class PlayingCard:
    """Class -- PlayingCard Represents a playing card. Attributes: value -- the card's value, an integer. suit -- the card's suit, a string"""

    def __init__(self, value, suit):
        """Constructor -- creates a new instance of PlayingCard Parameters: self -- the current PlayingCard object value -- the card's value, an integer suit -- the card's suit, a string"""
        <|body_0|>

    def set_name(self):
        """Method -- set_name Helper method to set the name of special cards. Parameter: self -- The current PlayingCard object Returns: Nothing. Sets the name attribute if applicable."""
        <|body_1|>

    def __str__(self):
        """Method -- __str__ Creates a string representation of the PlayingCard Parameter: self -- The current PlayingCard object Returns: A string representation of the PlayingCard."""
        <|body_2|>

    def __eq__(self, other):
        """Method -- __eq__ Checks if two objects are equal Parameters: self -- The current PlayingCard object other -- An object to compare self to. Returns: True if the two objects are equal, False otherwise."""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        self.value = value
        self.suit = suit
        self.set_name()
<|end_body_0|>

<|body_start_1|>
        NAMES = {1: 'Ace', 11: 'Jack', 12: 'Queen', 13: 'King'}
        if self.value in NAMES:
            self.name = NAMES[self.value]
<|end_body_1|>

<|body_start_2|>
        if self.name is not None:
            return '{} of {}'.format(self.name, self.suit)
        return '{} of {}'.format(self.value, self.suit)
<|end_body_2|>

<|body_start_3|>
        if type(self) != type(other):
            return False
        return self.value == other.value and self.suit == other.suit
<|end_body_3|>

Solution:
class PlayingCard:
    """Class -- PlayingCard Represents a playing card. Attributes: value -- the card's value, an integer. suit -- the card's suit, a string"""

    def __init__(self, value, suit):
        """Constructor -- creates a new instance of PlayingCard Parameters: self -- the current PlayingCard object value -- the card's value, an integer suit -- the card's suit, a string"""
        self.value = value
        self.suit = suit
        self.set_name()

    def set_name(self):
        """Method -- set_name Helper method to set the name of special cards. Parameter: self -- The current PlayingCard object Returns: Nothing. Sets the name attribute if applicable."""
        NAMES = {1: 'Ace', 11: 'Jack', 12: 'Queen', 13: 'King'}
        if self.value in NAMES:
            self.name = NAMES[self.value]

    def __str__(self):
        """Method -- __str__ Creates a string representation of the PlayingCard Parameter: self -- The current PlayingCard object Returns: A string representation of the PlayingCard."""
        if self.name is not None:
            return '{} of {}'.format(self.name, self.suit)
        return '{} of {}'.format(self.value, self.suit)

    def __eq__(self, other):
        """Method -- __eq__ Checks if two objects are equal Parameters: self -- The current PlayingCard object other -- An object to compare self to. Returns: True if the two objects are equal, False otherwise."""
        if type(self) != type(other):
            return False
        return self.value == other.value and self.suit == other.suit


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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def nthUglyNumber(self, n): :type n: int :rtype: int
- def nthUglyNumber_TLE(self, n): :type n: int :rtype: int

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def nthUglyNumber(self, n): :type n: int :rtype: int
- def nthUglyNumber_TLE(self, n): :type n: int :rtype: int

<|skeleton|>
class Solution:

    def nthUglyNumber(self, n):
        """:type n: int :rtype: int"""
        <|body_0|>

    def nthUglyNumber_TLE(self, n):
        """:type n: int :rtype: int"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        heap = []
        heapq.heappush(heap, 1)
        for _ in range(n):
            ugly = heapq.heappop(heap)
            if ugly % 2 == 0:
                heapq.heappush(heap, ugly * 2)
            elif ugly % 3 == 0:
                heapq.heappush(heap, ugly * 2)
                heapq.heappush(heap, ugly * 3)
            else:
                heapq.heappush(heap, ugly * 2)
                heapq.heappush(heap, ugly * 3)
                heapq.heappush(heap, ugly * 5)
        return ugly
<|end_body_0|>

<|body_start_1|>
        records = set()
        records |= set([1, 2, 3, 5])
        count = 0
        nth_num = 0
        num = 0
        while count < n:
            nth_num += 1
            num = nth_num
            for d in (2, 3, 5):
                while num % d == 0:
                    n_new = num // d
                    if n_new in records:
                        num = 1
                        break
                    num = n_new
            if num == 1:
                count += 1
                records.add(nth_num)
        return nth_num
<|end_body_1|>

Solution:
class Solution:
    def nthUglyNumber(self, n):
        """:type n: int :rtype: int"""
        heap = []
        heapq.heappush(heap, 1)
        for _ in range(n):
            ugly = heapq.heappop(heap)
            if ugly % 2 == 0:
                heapq.heappush(heap, ugly * 2)
            elif ugly % 3 == 0:
                heapq.heappush(heap, ugly * 2)
                heapq.heappush(heap, ugly * 3)
            else:
                heapq.heappush(heap, ugly * 2)
                heapq.heappush(heap, ugly * 3)
                heapq.heappush(heap, ugly * 5)
        return ugly

    def nthUglyNumber_TLE(self, n):
        """:type n: int :rtype: int"""
        records = set()
        records |= set([1, 2, 3, 5])
        count = 0
        nth_num = 0
        num = 0
        while count < n:
            nth_num += 1
            num = nth_num
            for d in (2, 3, 5):
                while num % d == 0:
                    n_new = num // d
                    if n_new in records:
                        num = 1
                        break
                    num = n_new
            if num == 1:
                count += 1
                records.add(nth_num)
        return nth_num


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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def rob(self, nums): :type nums: List[int] :rtype: int
- def rob_2variables(self, nums): time O(n) space O(1) :type nums: List[int] :rtype: int

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def rob(self, nums): :type nums: List[int] :rtype: int
- def rob_2variables(self, nums): time O(n) space O(1) :type nums: List[int] :rtype: int

<|skeleton|>
class Solution:

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

    def rob_2variables(self, nums):
        """time O(n) space O(1) :type nums: List[int] :rtype: int"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        if len(nums) == 1:
            return nums[0]

        def my_rob(nums):
            if not nums:
                return 0
            if len(nums) == 1:
                return nums[0]
            memo = [0] * len(nums)
            memo[0] = nums[0]
            memo[1] = max(memo[0], nums[1])
            for i in range(2, len(nums)):
                memo[i] = max(memo[i - 2] + nums[i], memo[i - 1])
            return memo[len(nums) - 1]
        return max(my_rob(nums[1:]), my_rob(nums[:-1]))
<|end_body_0|>

<|body_start_1|>
        if len(nums) == 1:
            return nums[0]

        def my_rob(nums):
            if not nums:
                return 0
            if len(nums) == 1:
                return nums[0]
            prev1 = prev2 = 0
            for num in nums:
                temp = prev1
                prev1 = max(prev1, prev2 + num)
                prev2 = temp
            return prev1
        return max(my_rob(nums[1:]), my_rob(nums[:-1]))
<|end_body_1|>

Solution:
class Solution:
    def rob(self, nums):
        """:type nums: List[int] :rtype: int"""
        if len(nums) == 1:
            return nums[0]

        def my_rob(nums):
            if not nums:
                return 0
            if len(nums) == 1:
                return nums[0]
            memo = [0] * len(nums)
            memo[0] = nums[0]
            memo[1] = max(memo[0], nums[1])
            for i in range(2, len(nums)):
                memo[i] = max(memo[i - 2] + nums[i], memo[i - 1])
            return memo[len(nums) - 1]
        return max(my_rob(nums[1:]), my_rob(nums[:-1]))

    def rob_2variables(self, nums):
        """time O(n) space O(1) :type nums: List[int] :rtype: int"""
        if len(nums) == 1:
            return nums[0]

        def my_rob(nums):
            if not nums:
                return 0
            if len(nums) == 1:
                return nums[0]
            prev1 = prev2 = 0
            for num in nums:
                temp = prev1
                prev1 = max(prev1, prev2 + num)
                prev2 = temp
            return prev1
        return max(my_rob(nums[1:]), my_rob(nums[:-1]))


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

Class description:
Container for storing model grid related variables.

Method signatures and docstrings:
- def prepare_coordinates(self): Prepare a range of variables related to the grid coordinates: - xs, ys: 1d-arrays containing the x and y coordinates in the grid CRS. - X, Y, 2d-arrays containing the x and y coordinates for each grid point. - all_points: (N, 2)-array containing (x, y) coordinates of all grid points. - roi_points: (N, 2)-array containing (x, y) coordinates of all ROI points. - roi_idxs: (N, 2)-array containing (row, col) indexes of all ROI points. - roi_idxs_flat: 1d-array containing the flattened (1d) indexes of all ROI points
- def prepare_roi_coordinates(self): Update the roi_points and roi_idxs variables using the ROI field.

Implement the Python class `ModelGrid` described below.

Class description:
Container for storing model grid related variables.

Method signatures and docstrings:
- def prepare_coordinates(self): Prepare a range of variables related to the grid coordinates: - xs, ys: 1d-arrays containing the x and y coordinates in the grid CRS. - X, Y, 2d-arrays containing the x and y coordinates for each grid point. - all_points: (N, 2)-array containing (x, y) coordinates of all grid points. - roi_points: (N, 2)-array containing (x, y) coordinates of all ROI points. - roi_idxs: (N, 2)-array containing (row, col) indexes of all ROI points. - roi_idxs_flat: 1d-array containing the flattened (1d) indexes of all ROI points
- def prepare_roi_coordinates(self): Update the roi_points and roi_idxs variables using the ROI field.

<|skeleton|>
class ModelGrid:
    """Container for storing model grid related variables."""

    def prepare_coordinates(self):
        """Prepare a range of variables related to the grid coordinates: - xs, ys: 1d-arrays containing the x and y coordinates in the grid CRS. - X, Y, 2d-arrays containing the x and y coordinates for each grid point. - all_points: (N, 2)-array containing (x, y) coordinates of all grid points. - roi_points: (N, 2)-array containing (x, y) coordinates of all ROI points. - roi_idxs: (N, 2)-array containing (row, col) indexes of all ROI points. - roi_idxs_flat: 1d-array containing the flattened (1d) indexes of all ROI points"""
        <|body_0|>

    def prepare_roi_coordinates(self):
        """Update the roi_points and roi_idxs variables using the ROI field."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        transform = self.transform
        if transform.a < 0 or transform.e > 0:
            raise NotImplementedError
        x_min = transform.xoff
        x_max = x_min + self.cols * self.resolution
        y_max = transform.yoff
        y_min = y_max - self.rows * self.resolution
        x_range, y_range = rasterio.transform.xy(self.transform, [0, self.rows - 1], [0, self.cols - 1])
        xs = np.linspace(x_range[0], x_range[1], self.cols)
        ys = np.linspace(y_range[0], y_range[1], self.rows)
        X, Y = np.meshgrid(xs, ys)
        center_x = xs.mean()
        center_y = ys.mean()
        center_lon, center_lat = transform_coords(center_x, center_y, self.crs, constants.CRS_WGS84)
        self.x_min = x_min
        self.x_max = x_max
        self.y_min = y_min
        self.y_max = y_max
        self.xs = xs
        self.ys = ys
        self.X = X
        self.Y = Y
        self.all_points = np.column_stack((X.flat, Y.flat))
        self.center_lon = center_lon
        self.center_lat = center_lat
        self.prepare_roi_coordinates()
<|end_body_0|>

<|body_start_1|>
        if 'roi' not in self:
            self.roi = np.ones((self.rows, self.cols), dtype=bool)
        roi_xs = self.X[self.roi]
        roi_ys = self.Y[self.roi]
        self.roi_points = np.column_stack((roi_xs, roi_ys))
        self.roi_idxs = np.array(np.where(self.roi)).T
        self.roi_idxs_flat = np.where(self.roi.flat)[0]
<|end_body_1|>

Solution:
class ModelGrid:
    """Container for storing model grid related variables."""

    def prepare_coordinates(self):
        """Prepare a range of variables related to the grid coordinates: - xs, ys: 1d-arrays containing the x and y coordinates in the grid CRS. - X, Y, 2d-arrays containing the x and y coordinates for each grid point. - all_points: (N, 2)-array containing (x, y) coordinates of all grid points. - roi_points: (N, 2)-array containing (x, y) coordinates of all ROI points. - roi_idxs: (N, 2)-array containing (row, col) indexes of all ROI points. - roi_idxs_flat: 1d-array containing the flattened (1d) indexes of all ROI points"""
        transform = self.transform
        if transform.a < 0 or transform.e > 0:
            raise NotImplementedError
        x_min = transform.xoff
        x_max = x_min + self.cols * self.resolution
        y_max = transform.yoff
        y_min = y_max - self.rows * self.resolution
        x_range, y_range = rasterio.transform.xy(self.transform, [0, self.rows - 1], [0, self.cols - 1])
        xs = np.linspace(x_range[0], x_range[1], self.cols)
        ys = np.linspace(y_range[0], y_range[1], self.rows)
        X, Y = np.meshgrid(xs, ys)
        center_x = xs.mean()
        center_y = ys.mean()
        center_lon, center_lat = transform_coords(center_x, center_y, self.crs, constants.CRS_WGS84)
        self.x_min = x_min
        self.x_max = x_max
        self.y_min = y_min
        self.y_max = y_max
        self.xs = xs
        self.ys = ys
        self.X = X
        self.Y = Y
        self.all_points = np.column_stack((X.flat, Y.flat))
        self.center_lon = center_lon
        self.center_lat = center_lat
        self.prepare_roi_coordinates()

    def prepare_roi_coordinates(self):
        """Update the roi_points and roi_idxs variables using the ROI field."""
        if 'roi' not in self:
            self.roi = np.ones((self.rows, self.cols), dtype=bool)
        roi_xs = self.X[self.roi]
        roi_ys = self.Y[self.roi]
        self.roi_points = np.column_stack((roi_xs, roi_ys))
        self.roi_idxs = np.array(np.where(self.roi)).T
        self.roi_idxs_flat = np.where(self.roi.flat)[0]


get

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

Class description:
Implement the GroupMembers class.

Method signatures and docstrings:
- def get(self, request, group_id, format=None): Get all group members.
- def post(self, request, group_id): Add a group member.

Implement the Python class `GroupMembers` described below.

Class description:
Implement the GroupMembers class.

Method signatures and docstrings:
- def get(self, request, group_id, format=None): Get all group members.
- def post(self, request, group_id): Add a group member.

<|skeleton|>
class GroupMembers:

    def get(self, request, group_id, format=None):
        """Get all group members."""
        <|body_0|>

    def post(self, request, group_id):
        """Add a group member."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        try:
            avatar_size = int(request.GET.get('avatar_size', AVATAR_DEFAULT_SIZE))
        except ValueError:
            avatar_size = AVATAR_DEFAULT_SIZE
        try:
            if not is_group_member(group_id, request.user.username):
                error_msg = 'Permission denied.'
                return api_error(status.HTTP_403_FORBIDDEN, error_msg)
            members = ccnet_api.get_group_members(group_id)
        except RpcsyncwerkError as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)
        group_members = []
        is_admin = request.GET.get('is_admin', 'false')
        for m in members:
            if is_admin == 'true' and (not m.is_staff):
                continue
            member_info = get_group_member_info(request, group_id, m.user_name, avatar_size)
            group_members.append(member_info)
        return Response(group_members)
<|end_body_0|>

<|body_start_1|>
        username = request.user.username
        if not is_group_admin_or_owner(group_id, username):
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)
        email = request.data.get('email', None)
        try:
            User.objects.get(email=email)
        except User.DoesNotExist:
            error_msg = 'User %s not found.' % email
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)
        try:
            if is_group_member(group_id, email):
                error_msg = _(u'User %s is already a group member.') % email2nickname(email)
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
            if is_org_context(request):
                org_id = request.user.org.org_id
                if not ccnet_api.org_user_exists(org_id, email):
                    error_msg = _(u'User %s not found in organization.') % email2nickname(email)
                    return api_error(status.HTTP_404_NOT_FOUND, error_msg)
            ccnet_api.group_add_member(group_id, username, email)
            add_user_to_group.send(sender=None, group_staff=username, group_id=group_id, added_user=email)
        except RpcsyncwerkError as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)
        member_info = get_group_member_info(request, group_id, email)
        return Response(member_info, status=status.HTTP_201_CREATED)
<|end_body_1|>

Solution:
class GroupMembers:
    def get(self, request, group_id, format=None):
        """Get all group members."""
        try:
            avatar_size = int(request.GET.get('avatar_size', AVATAR_DEFAULT_SIZE))
        except ValueError:
            avatar_size = AVATAR_DEFAULT_SIZE
        try:
            if not is_group_member(group_id, request.user.username):
                error_msg = 'Permission denied.'
                return api_error(status.HTTP_403_FORBIDDEN, error_msg)
            members = ccnet_api.get_group_members(group_id)
        except RpcsyncwerkError as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)
        group_members = []
        is_admin = request.GET.get('is_admin', 'false')
        for m in members:
            if is_admin == 'true' and (not m.is_staff):
                continue
            member_info = get_group_member_info(request, group_id, m.user_name, avatar_size)
            group_members.append(member_info)
        return Response(group_members)

    def post(self, request, group_id):
        """Add a group member."""
        username = request.user.username
        if not is_group_admin_or_owner(group_id, username):
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)
        email = request.data.get('email', None)
        try:
            User.objects.get(email=email)
        except User.DoesNotExist:
            error_msg = 'User %s not found.' % email
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)
        try:
            if is_group_member(group_id, email):
                error_msg = _(u'User %s is already a group member.') % email2nickname(email)
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
            if is_org_context(request):
                org_id = request.user.org.org_id
                if not ccnet_api.org_user_exists(org_id, email):
                    error_msg = _(u'User %s not found in organization.') % email2nickname(email)
                    return api_error(status.HTTP_404_NOT_FOUND, error_msg)
            ccnet_api.group_add_member(group_id, username, email)
            add_user_to_group.send(sender=None, group_staff=username, group_id=group_id, added_user=email)
        except RpcsyncwerkError as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)
        member_info = get_group_member_info(request, group_id, email)
        return Response(member_info, status=status.HTTP_201_CREATED)


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

Class description:
Manage dbcollection configurations and stores them inside a cache file stored in disk. Attributes ---------- cache_filename : str Cache file path + name. cache_dir : str Default directory to store all dataset's metadata files. download_dir : str Default save dir path for downloaded data. data : dict Cache contents.

Method signatures and docstrings:
- def __init__(self): Initializes the class.
- def info_cache(self): Prints the information of the cache.

Implement the Python class `CacheManager` described below.

Class description:
Manage dbcollection configurations and stores them inside a cache file stored in disk. Attributes ---------- cache_filename : str Cache file path + name. cache_dir : str Default directory to store all dataset's metadata files. download_dir : str Default save dir path for downloaded data. data : dict Cache contents.

Method signatures and docstrings:
- def __init__(self): Initializes the class.
- def info_cache(self): Prints the information of the cache.

<|skeleton|>
class CacheManager:
    """Manage dbcollection configurations and stores them inside a cache file stored in disk. Attributes ---------- cache_filename : str Cache file path + name. cache_dir : str Default directory to store all dataset's metadata files. download_dir : str Default save dir path for downloaded data. data : dict Cache contents."""

    def __init__(self):
        """Initializes the class."""
        <|body_0|>

    def info_cache(self):
        """Prints the information of the cache."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.manager = CacheDataManager()
        self.info = CacheManagerInfo(self.manager)
        self.dataset = CacheManagerDataset(self.manager)
        self.task = CacheManagerTask(self.manager)
        self.category = CacheManagerCategory(self.manager)
<|end_body_0|>

<|body_start_1|>
        self.info.info()
        self.dataset.info()
        self.category.info()
<|end_body_1|>

Solution:
class CacheManager:
    """Manage dbcollection configurations and stores them inside a cache file stored in disk. Attributes ---------- cache_filename : str Cache file path + name. cache_dir : str Default directory to store all dataset's metadata files. download_dir : str Default save dir path for downloaded data. data : dict Cache contents."""

    def __init__(self):
        """Initializes the class."""
        self.manager = CacheDataManager()
        self.info = CacheManagerInfo(self.manager)
        self.dataset = CacheManagerDataset(self.manager)
        self.task = CacheManagerTask(self.manager)
        self.category = CacheManagerCategory(self.manager)

    def info_cache(self):
        """Prints the information of the cache."""
        self.info.info()
        self.dataset.info()
        self.category.info()


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

Class description:
Implement the InterpolateSplineTest class.

Method signatures and docstrings:
- def test_1d_linear_interpolation(self): For 1d linear interpolation, we can compare directly to scipy.
- def test_1d_interpolation(self): Regression test for interpolation with 1-D points.
- def test_nd_linear_interpolation(self): Regression test for interpolation with N-D points.
- def test_interpolation_gradient(self): Make sure that backprop can run. Correctness of gradients is assumed. Here, we create a use a small 'training' set and a more densely-sampled set of query points, for which we know the true value in advance. The goal is to choose x locations for the training data such that interpolating using this training data yields the best reconstruction for the function values at the query points. The training data locations are optimized iteratively using gradient descent.

Implement the Python class `InterpolateSplineTest` described below.

Class description:
Implement the InterpolateSplineTest class.

Method signatures and docstrings:
- def test_1d_linear_interpolation(self): For 1d linear interpolation, we can compare directly to scipy.
- def test_1d_interpolation(self): Regression test for interpolation with 1-D points.
- def test_nd_linear_interpolation(self): Regression test for interpolation with N-D points.
- def test_interpolation_gradient(self): Make sure that backprop can run. Correctness of gradients is assumed. Here, we create a use a small 'training' set and a more densely-sampled set of query points, for which we know the true value in advance. The goal is to choose x locations for the training data such that interpolating using this training data yields the best reconstruction for the function values at the query points. The training data locations are optimized iteratively using gradient descent.

<|skeleton|>
class InterpolateSplineTest:

    def test_1d_linear_interpolation(self):
        """For 1d linear interpolation, we can compare directly to scipy."""
        <|body_0|>

    def test_1d_interpolation(self):
        """Regression test for interpolation with 1-D points."""
        <|body_1|>

    def test_nd_linear_interpolation(self):
        """Regression test for interpolation with N-D points."""
        <|body_2|>

    def test_interpolation_gradient(self):
        """Make sure that backprop can run. Correctness of gradients is assumed. Here, we create a use a small 'training' set and a more densely-sampled set of query points, for which we know the true value in advance. The goal is to choose x locations for the training data such that interpolating using this training data yields the best reconstruction for the function values at the query points. The training data locations are optimized iteratively using gradient descent."""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        tp = _QuadraticPlusSinProblem1D()
        query_points, _, train_points, train_values = tp.get_problem(extrapolate=False, dtype='float64')
        interpolation_order = 1
        with ops.name_scope('interpolator'):
            interpolator = interpolate_spline.interpolate_spline(train_points, train_values, query_points, interpolation_order)
            with self.test_session() as sess:
                fetches = [query_points, train_points, train_values, interpolator]
                query_points_, train_points_, train_values_, interp_ = sess.run(fetches)
                interp_ = interp_[0, :, 0]
                query_points_ = query_points_[0, :, 0]
                train_points_ = train_points_[0, :, 0]
                train_values_ = train_values_[0, :, 0]
                scipy_interp_function = sc_interpolate.interp1d(train_points_, train_values_, kind='linear')
                scipy_interpolation = scipy_interp_function(query_points_)
                scipy_interpolation_on_train = scipy_interp_function(train_points_)
                tol = 0.001
                self.assertAllClose(train_values_, scipy_interpolation_on_train, atol=tol, rtol=tol)
                self.assertAllClose(interp_, scipy_interpolation, atol=tol, rtol=tol)
<|end_body_0|>

<|body_start_1|>
        tp = _QuadraticPlusSinProblem1D()
        query_points, _, train_points, train_values = tp.get_problem(dtype='float64')
        for order in (1, 2, 3):
            for reg_weight in (0, 0.01):
                interpolator = interpolate_spline.interpolate_spline(train_points, train_values, query_points, order, reg_weight)
                target_interpolation = tp.HARDCODED_QUERY_VALUES[order, reg_weight]
                target_interpolation = np.array(target_interpolation)
                with self.test_session() as sess:
                    interp_val = sess.run(interpolator)
                    self.assertAllClose(interp_val[0, :, 0], target_interpolation)
<|end_body_1|>

<|body_start_2|>
        tp = _QuadraticPlusSinProblemND()
        query_points, _, train_points, train_values = tp.get_problem(dtype='float64')
        for order in (1, 2, 3):
            for reg_weight in (0, 0.01):
                interpolator = interpolate_spline.interpolate_spline(train_points, train_values, query_points, order, reg_weight)
                target_interpolation = tp.HARDCODED_QUERY_VALUES[order, reg_weight]
                target_interpolation = np.array(target_interpolation)
                with self.test_session() as sess:
                    interp_val = sess.run(interpolator)
                    self.assertAllClose(interp_val[0, :, 0], target_interpolation)
<|end_body_2|>

<|body_start_3|>
        tp = _QuadraticPlusSinProblemND()
        query_points, query_values, train_points, train_values = tp.get_problem(optimizable=True)
        regularization = 0.001
        for interpolation_order in (1, 2, 3, 4):
            interpolator = interpolate_spline.interpolate_spline(train_points, train_values, query_points, interpolation_order, regularization)
            loss = math_ops.reduce_mean(math_ops.square(query_values - interpolator))
            optimizer = momentum.MomentumOptimizer(0.001, 0.9)
            grad = gradients.gradients(loss, [train_points])
            grad, _ = clip_ops.clip_by_global_norm(grad, 1.0)
            opt_func = optimizer.apply_gradients(zip(grad, [train_points]))
            init_op = variables.global_variables_initializer()
            with self.test_session() as sess:
                sess.run(init_op)
                for _ in range(100):
                    sess.run([loss, opt_func])
<|end_body_3|>

Solution:
class InterpolateSplineTest:
    def test_1d_linear_interpolation(self):
        """For 1d linear interpolation, we can compare directly to scipy."""
        tp = _QuadraticPlusSinProblem1D()
        query_points, _, train_points, train_values = tp.get_problem(extrapolate=False, dtype='float64')
        interpolation_order = 1
        with ops.name_scope('interpolator'):
            interpolator = interpolate_spline.interpolate_spline(train_points, train_values, query_points, interpolation_order)
            with self.test_session() as sess:
                fetches = [query_points, train_points, train_values, interpolator]
                query_points_, train_points_, train_values_, interp_ = sess.run(fetches)
                interp_ = interp_[0, :, 0]
                query_points_ = query_points_[0, :, 0]
                train_points_ = train_points_[0, :, 0]
                train_values_ = train_values_[0, :, 0]
                scipy_interp_function = sc_interpolate.interp1d(train_points_, train_values_, kind='linear')
                scipy_interpolation = scipy_interp_function(query_points_)
                scipy_interpolation_on_train = scipy_interp_function(train_points_)
                tol = 0.001
                self.assertAllClose(train_values_, scipy_interpolation_on_train, atol=tol, rtol=tol)
                self.assertAllClose(interp_, scipy_interpolation, atol=tol, rtol=tol)

    def test_1d_interpolation(self):
        """Regression test for interpolation with 1-D points."""
        tp = _QuadraticPlusSinProblem1D()
        query_points, _, train_points, train_values = tp.get_problem(dtype='float64')
        for order in (1, 2, 3):
            for reg_weight in (0, 0.01):
                interpolator = interpolate_spline.interpolate_spline(train_points, train_values, query_points, order, reg_weight)
                target_interpolation = tp.HARDCODED_QUERY_VALUES[order, reg_weight]
                target_interpolation = np.array(target_interpolation)
                with self.test_session() as sess:
                    interp_val = sess.run(interpolator)
                    self.assertAllClose(interp_val[0, :, 0], target_interpolation)

    def test_nd_linear_interpolation(self):
        """Regression test for interpolation with N-D points."""
        tp = _QuadraticPlusSinProblemND()
        query_points, _, train_points, train_values = tp.get_problem(dtype='float64')
        for order in (1, 2, 3):
            for reg_weight in (0, 0.01):
                interpolator = interpolate_spline.interpolate_spline(train_points, train_values, query_points, order, reg_weight)
                target_interpolation = tp.HARDCODED_QUERY_VALUES[order, reg_weight]
                target_interpolation = np.array(target_interpolation)
                with self.test_session() as sess:
                    interp_val = sess.run(interpolator)
                    self.assertAllClose(interp_val[0, :, 0], target_interpolation)

    def test_interpolation_gradient(self):
        """Make sure that backprop can run. Correctness of gradients is assumed. Here, we create a use a small 'training' set and a more densely-sampled set of query points, for which we know the true value in advance. The goal is to choose x locations for the training data such that interpolating using this training data yields the best reconstruction for the function values at the query points. The training data locations are optimized iteratively using gradient descent."""
        tp = _QuadraticPlusSinProblemND()
        query_points, query_values, train_points, train_values = tp.get_problem(optimizable=True)
        regularization = 0.001
        for interpolation_order in (1, 2, 3, 4):
            interpolator = interpolate_spline.interpolate_spline(train_points, train_values, query_points, interpolation_order, regularization)
            loss = math_ops.reduce_mean(math_ops.square(query_values - interpolator))
            optimizer = momentum.MomentumOptimizer(0.001, 0.9)
            grad = gradients.gradients(loss, [train_points])
            grad, _ = clip_ops.clip_by_global_norm(grad, 1.0)
            opt_func = optimizer.apply_gradients(zip(grad, [train_points]))
            init_op = variables.global_variables_initializer()
            with self.test_session() as sess:
                sess.run(init_op)
                for _ in range(100):
                    sess.run([loss, opt_func])


build

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

Class description:
TextCNN Layer 底层embedding layer, 再接多窗口多核卷积，最后最大池化max-pooling

Method signatures and docstrings:
- def __init__(self, in_hidden, max_seq_len, filter_sizes, num_filters, training, scope='text_cnn'): TextCNN初始化 Args: in_hidden: 输入层tensor, 通常是一个batch的词向量 max_seq_len: 序列最大长度 filter_sizes: array类型，所有卷积核的大小，支持多个窗口同时卷积 num_filters: 卷积核个数
- def build(self): TextCNN Layer层 Returns: 返回经过TextCNN后的隐层表示，shape是[batch, feature_dim=filter_sizes*num_filters]

Implement the Python class `TFTextCNNLayer` described below.

Class description:
TextCNN Layer 底层embedding layer, 再接多窗口多核卷积，最后最大池化max-pooling

Method signatures and docstrings:
- def __init__(self, in_hidden, max_seq_len, filter_sizes, num_filters, training, scope='text_cnn'): TextCNN初始化 Args: in_hidden: 输入层tensor, 通常是一个batch的词向量 max_seq_len: 序列最大长度 filter_sizes: array类型，所有卷积核的大小，支持多个窗口同时卷积 num_filters: 卷积核个数
- def build(self): TextCNN Layer层 Returns: 返回经过TextCNN后的隐层表示，shape是[batch, feature_dim=filter_sizes*num_filters]

<|skeleton|>
class TFTextCNNLayer:
    """TextCNN Layer 底层embedding layer, 再接多窗口多核卷积，最后最大池化max-pooling"""

    def __init__(self, in_hidden, max_seq_len, filter_sizes, num_filters, training, scope='text_cnn'):
        """TextCNN初始化 Args: in_hidden: 输入层tensor, 通常是一个batch的词向量 max_seq_len: 序列最大长度 filter_sizes: array类型，所有卷积核的大小，支持多个窗口同时卷积 num_filters: 卷积核个数"""
        <|body_0|>

    def build(self):
        """TextCNN Layer层 Returns: 返回经过TextCNN后的隐层表示，shape是[batch, feature_dim=filter_sizes*num_filters]"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        TFBaseLayer.__init__(self)
        self.in_hidden = in_hidden
        self.emb_size = self.in_hidden.get_shape()[-1]
        self.max_seq_len = max_seq_len
        self.filter_sizes = filter_sizes
        self.num_filters = num_filters
        self.training = training
        self.scope = scope
<|end_body_0|>

<|body_start_1|>
        embedded_words_expanded = tf.expand_dims(self.in_hidden, -1)
        pooled_outputs = []
        for i, filter_size in enumerate(self.filter_sizes):
            with tf.variable_scope(self.scope + '-' + str(filter_size), reuse=tf.AUTO_REUSE):
                filter_shape = [filter_size, self.emb_size, 1, self.num_filters]
                filters = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name='filters')
                W = tf.get_variable('W' + str(filter_size), shape=filter_shape, initializer=tf.truncated_normal_initializer(stddev=0.1))
                b = tf.get_variable('b' + str(filter_size), shape=[self.num_filters], initializer=tf.zeros_initializer())
                conv = tf.nn.conv2d(embedded_words_expanded, W, strides=[1, 1, 1, 1], padding='VALID', name='conv' + str(filter_size))
                conv = tf.add(conv, b)
                bn_conv = tf.layers.batch_normalization(conv, training=self.training, name='BN')
                hidden = tf.nn.relu(bn_conv, name='relu')
                pooled = tf.nn.max_pool(hidden, ksize=[1, self.max_seq_len - filter_size + 1, 1, 1], strides=[1, 1, 1, 1], padding='VALID', name='pool' + str(filter_size))
                pooled_outputs.append(pooled)
        feature_dim = self.num_filters * len(self.filter_sizes)
        h_pool = tf.concat(pooled_outputs, 3)
        output = tf.reshape(h_pool, [-1, feature_dim])
        return output
<|end_body_1|>

Solution:
class TFTextCNNLayer:
    """TextCNN Layer 底层embedding layer, 再接多窗口多核卷积，最后最大池化max-pooling"""

    def __init__(self, in_hidden, max_seq_len, filter_sizes, num_filters, training, scope='text_cnn'):
        """TextCNN初始化 Args: in_hidden: 输入层tensor, 通常是一个batch的词向量 max_seq_len: 序列最大长度 filter_sizes: array类型，所有卷积核的大小，支持多个窗口同时卷积 num_filters: 卷积核个数"""
        TFBaseLayer.__init__(self)
        self.in_hidden = in_hidden
        self.emb_size = self.in_hidden.get_shape()[-1]
        self.max_seq_len = max_seq_len
        self.filter_sizes = filter_sizes
        self.num_filters = num_filters
        self.training = training
        self.scope = scope

    def build(self):
        """TextCNN Layer层 Returns: 返回经过TextCNN后的隐层表示，shape是[batch, feature_dim=filter_sizes*num_filters]"""
        embedded_words_expanded = tf.expand_dims(self.in_hidden, -1)
        pooled_outputs = []
        for i, filter_size in enumerate(self.filter_sizes):
            with tf.variable_scope(self.scope + '-' + str(filter_size), reuse=tf.AUTO_REUSE):
                filter_shape = [filter_size, self.emb_size, 1, self.num_filters]
                filters = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name='filters')
                W = tf.get_variable('W' + str(filter_size), shape=filter_shape, initializer=tf.truncated_normal_initializer(stddev=0.1))
                b = tf.get_variable('b' + str(filter_size), shape=[self.num_filters], initializer=tf.zeros_initializer())
                conv = tf.nn.conv2d(embedded_words_expanded, W, strides=[1, 1, 1, 1], padding='VALID', name='conv' + str(filter_size))
                conv = tf.add(conv, b)
                bn_conv = tf.layers.batch_normalization(conv, training=self.training, name='BN')
                hidden = tf.nn.relu(bn_conv, name='relu')
                pooled = tf.nn.max_pool(hidden, ksize=[1, self.max_seq_len - filter_size + 1, 1, 1], strides=[1, 1, 1, 1], padding='VALID', name='pool' + str(filter_size))
                pooled_outputs.append(pooled)
        feature_dim = self.num_filters * len(self.filter_sizes)
        h_pool = tf.concat(pooled_outputs, 3)
        output = tf.reshape(h_pool, [-1, feature_dim])
        return output


predict

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

Class description:
Implement the BoostedDT class.

Method signatures and docstrings:
- def __init__(self, numBoostingIters=100, maxTreeDepth=3): Constructor Class Fields clfs : List object containing individual DecisionTree classifiers, in order of creation during boosting betas : List of beta values, in order of creation during boosting
- def fit(self, X, y, random_state=None): Trains the model. Be sure to initialize all individual Decision trees with the provided random_state value if provided. Arguments: X is an n-by-d Pandas Data Frame y is an n-by-1 Pandas Data Frame random_seed is an optional integer value
- def predict(self, X): Used the model to predict values for each instance in X Arguments: X is an n-by-d Pandas Data Frame Returns: an n-by-1 Pandas Data Frame of the predictions

Implement the Python class `BoostedDT` described below.

Class description:
Implement the BoostedDT class.

Method signatures and docstrings:
- def __init__(self, numBoostingIters=100, maxTreeDepth=3): Constructor Class Fields clfs : List object containing individual DecisionTree classifiers, in order of creation during boosting betas : List of beta values, in order of creation during boosting
- def fit(self, X, y, random_state=None): Trains the model. Be sure to initialize all individual Decision trees with the provided random_state value if provided. Arguments: X is an n-by-d Pandas Data Frame y is an n-by-1 Pandas Data Frame random_seed is an optional integer value
- def predict(self, X): Used the model to predict values for each instance in X Arguments: X is an n-by-d Pandas Data Frame Returns: an n-by-1 Pandas Data Frame of the predictions

<|skeleton|>
class BoostedDT:

    def __init__(self, numBoostingIters=100, maxTreeDepth=3):
        """Constructor Class Fields clfs : List object containing individual DecisionTree classifiers, in order of creation during boosting betas : List of beta values, in order of creation during boosting"""
        <|body_0|>

    def fit(self, X, y, random_state=None):
        """Trains the model. Be sure to initialize all individual Decision trees with the provided random_state value if provided. Arguments: X is an n-by-d Pandas Data Frame y is an n-by-1 Pandas Data Frame random_seed is an optional integer value"""
        <|body_1|>

    def predict(self, X):
        """Used the model to predict values for each instance in X Arguments: X is an n-by-d Pandas Data Frame Returns: an n-by-1 Pandas Data Frame of the predictions"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        self.clfs = []
        self.betas = []
        self.numBoostingIters = numBoostingIters
        self.maxTreeDepth = maxTreeDepth
        self.K = None
        self.classes = None
<|end_body_0|>

<|body_start_1|>
        X = X.to_numpy()
        y = y.to_numpy()
        n, d = X.shape
        y = y.reshape(-1, 1)
        self.classes = np.unique(y)
        self.K = len(self.classes)
        weights = np.full(n, 1 / n).reshape(-1, 1)
        for iter_num in range(self.numBoostingIters):
            h = tree.DecisionTreeClassifier(max_depth=self.maxTreeDepth, random_state=random_state)
            h.fit(X, y, sample_weight=weights.flatten())
            self.clfs.append(h)
            y_pred = h.predict(X).reshape(-1, 1)
            epsilon = np.sum((y_pred != y) * weights)
            beta = np.log((self.K - 1) * (1 - epsilon) / epsilon) / 2
            self.betas.append(beta)
            weights[y_pred == y] *= np.exp(-beta)
            weights[y_pred != y] *= np.exp(beta)
            weights /= sum(weights)
<|end_body_1|>

<|body_start_2|>
        X = X.to_numpy()
        n, d = X.shape
        proba = np.zeros((n, self.K))
        for iter_num in range(self.numBoostingIters):
            proba += self.clfs[iter_num].predict_proba(X)
        max_proba = np.argmax(proba, axis=1).reshape(-1)
        pred_array = np.tile(self.classes, (n, 1))
        y_pred = np.choose(max_proba, pred_array.T).reshape(-1, 1)
        return pd.DataFrame(y_pred)
<|end_body_2|>

Solution:
class BoostedDT:
    def __init__(self, numBoostingIters=100, maxTreeDepth=3):
        """Constructor Class Fields clfs : List object containing individual DecisionTree classifiers, in order of creation during boosting betas : List of beta values, in order of creation during boosting"""
        self.clfs = []
        self.betas = []
        self.numBoostingIters = numBoostingIters
        self.maxTreeDepth = maxTreeDepth
        self.K = None
        self.classes = None

    def fit(self, X, y, random_state=None):
        """Trains the model. Be sure to initialize all individual Decision trees with the provided random_state value if provided. Arguments: X is an n-by-d Pandas Data Frame y is an n-by-1 Pandas Data Frame random_seed is an optional integer value"""
        X = X.to_numpy()
        y = y.to_numpy()
        n, d = X.shape
        y = y.reshape(-1, 1)
        self.classes = np.unique(y)
        self.K = len(self.classes)
        weights = np.full(n, 1 / n).reshape(-1, 1)
        for iter_num in range(self.numBoostingIters):
            h = tree.DecisionTreeClassifier(max_depth=self.maxTreeDepth, random_state=random_state)
            h.fit(X, y, sample_weight=weights.flatten())
            self.clfs.append(h)
            y_pred = h.predict(X).reshape(-1, 1)
            epsilon = np.sum((y_pred != y) * weights)
            beta = np.log((self.K - 1) * (1 - epsilon) / epsilon) / 2
            self.betas.append(beta)
            weights[y_pred == y] *= np.exp(-beta)
            weights[y_pred != y] *= np.exp(beta)
            weights /= sum(weights)

    def predict(self, X):
        """Used the model to predict values for each instance in X Arguments: X is an n-by-d Pandas Data Frame Returns: an n-by-1 Pandas Data Frame of the predictions"""
        X = X.to_numpy()
        n, d = X.shape
        proba = np.zeros((n, self.K))
        for iter_num in range(self.numBoostingIters):
            proba += self.clfs[iter_num].predict_proba(X)
        max_proba = np.argmax(proba, axis=1).reshape(-1)
        pred_array = np.tile(self.classes, (n, 1))
        y_pred = np.choose(max_proba, pred_array.T).reshape(-1, 1)
        return pd.DataFrame(y_pred)


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

Class description:
AdminCommands contains all the commands for processing the commands from the parent process.

Method signatures and docstrings:
- def get_command(command_name): Call to return the AdminCommand object. Args: command_name: AdminCommand name Returns: AdminCommand object
- def register_command(command_processor: CommandProcessor): Call to register the AdminCommand processor. Args: command_processor: AdminCommand processor

Implement the Python class `AdminCommands` described below.

Class description:
AdminCommands contains all the commands for processing the commands from the parent process.

Method signatures and docstrings:
- def get_command(command_name): Call to return the AdminCommand object. Args: command_name: AdminCommand name Returns: AdminCommand object
- def register_command(command_processor: CommandProcessor): Call to register the AdminCommand processor. Args: command_processor: AdminCommand processor

<|skeleton|>
class AdminCommands:
    """AdminCommands contains all the commands for processing the commands from the parent process."""

    def get_command(command_name):
        """Call to return the AdminCommand object. Args: command_name: AdminCommand name Returns: AdminCommand object"""
        <|body_0|>

    def register_command(command_processor: CommandProcessor):
        """Call to register the AdminCommand processor. Args: command_processor: AdminCommand processor"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        for command in AdminCommands.commands:
            if command_name == command.get_command_name():
                return command
        return None
<|end_body_0|>

<|body_start_1|>
        if not isinstance(command_processor, CommandProcessor):
            raise TypeError('command_processor must be an instance of CommandProcessor, but got {}'.format(type(command_processor)))
        AdminCommands.commands.append(command_processor)
<|end_body_1|>

Solution:
class AdminCommands:
    """AdminCommands contains all the commands for processing the commands from the parent process."""

    def get_command(command_name):
        """Call to return the AdminCommand object. Args: command_name: AdminCommand name Returns: AdminCommand object"""
        for command in AdminCommands.commands:
            if command_name == command.get_command_name():
                return command
        return None

    def register_command(command_processor: CommandProcessor):
        """Call to register the AdminCommand processor. Args: command_processor: AdminCommand processor"""
        if not isinstance(command_processor, CommandProcessor):
            raise TypeError('command_processor must be an instance of CommandProcessor, but got {}'.format(type(command_processor)))
        AdminCommands.commands.append(command_processor)


run

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

Class description:
Tfx runner on Beam.

Method signatures and docstrings:
- def __init__(self, beam_orchestrator_args: Optional[List[str]]=None, config: Optional[pipeline_config.PipelineConfig]=None): Initializes BeamDagRunner as a TFX orchestrator. Args: beam_orchestrator_args: beam args for the beam orchestrator. Note that this is different from the beam_pipeline_args within additional_pipeline_args, which is for beam pipelines in components. config: Optional pipeline config for customizing the launching of each component. Defaults to pipeline config that supports InProcessComponentLauncher and DockerComponentLauncher.
- def run(self, tfx_pipeline: pipeline.Pipeline) -> None: Deploys given logical pipeline on Beam. Args: tfx_pipeline: Logical pipeline containing pipeline args and components.

Implement the Python class `BeamDagRunner` described below.

Class description:
Tfx runner on Beam.

Method signatures and docstrings:
- def __init__(self, beam_orchestrator_args: Optional[List[str]]=None, config: Optional[pipeline_config.PipelineConfig]=None): Initializes BeamDagRunner as a TFX orchestrator. Args: beam_orchestrator_args: beam args for the beam orchestrator. Note that this is different from the beam_pipeline_args within additional_pipeline_args, which is for beam pipelines in components. config: Optional pipeline config for customizing the launching of each component. Defaults to pipeline config that supports InProcessComponentLauncher and DockerComponentLauncher.
- def run(self, tfx_pipeline: pipeline.Pipeline) -> None: Deploys given logical pipeline on Beam. Args: tfx_pipeline: Logical pipeline containing pipeline args and components.

<|skeleton|>
class BeamDagRunner:
    """Tfx runner on Beam."""

    def __init__(self, beam_orchestrator_args: Optional[List[str]]=None, config: Optional[pipeline_config.PipelineConfig]=None):
        """Initializes BeamDagRunner as a TFX orchestrator. Args: beam_orchestrator_args: beam args for the beam orchestrator. Note that this is different from the beam_pipeline_args within additional_pipeline_args, which is for beam pipelines in components. config: Optional pipeline config for customizing the launching of each component. Defaults to pipeline config that supports InProcessComponentLauncher and DockerComponentLauncher."""
        <|body_0|>

    def run(self, tfx_pipeline: pipeline.Pipeline) -> None:
        """Deploys given logical pipeline on Beam. Args: tfx_pipeline: Logical pipeline containing pipeline args and components."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        if config is None:
            config = pipeline_config.PipelineConfig(supported_launcher_classes=[in_process_component_launcher.InProcessComponentLauncher, docker_component_launcher.DockerComponentLauncher])
        super().__init__(config)
        self._beam_orchestrator_args = beam_orchestrator_args
<|end_body_0|>

<|body_start_1|>
        tfx_pipeline.pipeline_info.run_id = datetime.datetime.now().isoformat()
        with telemetry_utils.scoped_labels({telemetry_utils.LABEL_TFX_RUNNER: 'beam'}):
            with beam.Pipeline(argv=self._beam_orchestrator_args) as p:
                root = p | 'CreateRoot' >> beam.Create([None])
                signal_map = {}
                for component in tfx_pipeline.components:
                    if isinstance(component, base_component.BaseComponent):
                        component._resolve_pip_dependencies(tfx_pipeline.pipeline_info.pipeline_root)
                    component_id = component.id
                    signals_to_wait = []
                    if component.upstream_nodes:
                        for upstream_node in component.upstream_nodes:
                            assert upstream_node in signal_map, 'Components is not in topological order'
                            signals_to_wait.append(signal_map[upstream_node])
                    absl.logging.info('Component %s depends on %s.', component_id, [s.producer.full_label for s in signals_to_wait])
                    component_launcher_class, component_config = config_utils.find_component_launch_info(self._config, component)
                    signal_map[component] = root | 'Run[%s]' % component_id >> beam.ParDo(_ComponentAsDoFn(component, component_launcher_class, component_config, tfx_pipeline), *[beam.pvalue.AsIter(s) for s in signals_to_wait])
                    absl.logging.info('Component %s is scheduled.', component_id)
<|end_body_1|>

Solution:
class BeamDagRunner:
    """Tfx runner on Beam."""

    def __init__(self, beam_orchestrator_args: Optional[List[str]]=None, config: Optional[pipeline_config.PipelineConfig]=None):
        """Initializes BeamDagRunner as a TFX orchestrator. Args: beam_orchestrator_args: beam args for the beam orchestrator. Note that this is different from the beam_pipeline_args within additional_pipeline_args, which is for beam pipelines in components. config: Optional pipeline config for customizing the launching of each component. Defaults to pipeline config that supports InProcessComponentLauncher and DockerComponentLauncher."""
        if config is None:
            config = pipeline_config.PipelineConfig(supported_launcher_classes=[in_process_component_launcher.InProcessComponentLauncher, docker_component_launcher.DockerComponentLauncher])
        super().__init__(config)
        self._beam_orchestrator_args = beam_orchestrator_args

    def run(self, tfx_pipeline: pipeline.Pipeline) -> None:
        """Deploys given logical pipeline on Beam. Args: tfx_pipeline: Logical pipeline containing pipeline args and components."""
        tfx_pipeline.pipeline_info.run_id = datetime.datetime.now().isoformat()
        with telemetry_utils.scoped_labels({telemetry_utils.LABEL_TFX_RUNNER: 'beam'}):
            with beam.Pipeline(argv=self._beam_orchestrator_args) as p:
                root = p | 'CreateRoot' >> beam.Create([None])
                signal_map = {}
                for component in tfx_pipeline.components:
                    if isinstance(component, base_component.BaseComponent):
                        component._resolve_pip_dependencies(tfx_pipeline.pipeline_info.pipeline_root)
                    component_id = component.id
                    signals_to_wait = []
                    if component.upstream_nodes:
                        for upstream_node in component.upstream_nodes:
                            assert upstream_node in signal_map, 'Components is not in topological order'
                            signals_to_wait.append(signal_map[upstream_node])
                    absl.logging.info('Component %s depends on %s.', component_id, [s.producer.full_label for s in signals_to_wait])
                    component_launcher_class, component_config = config_utils.find_component_launch_info(self._config, component)
                    signal_map[component] = root | 'Run[%s]' % component_id >> beam.ParDo(_ComponentAsDoFn(component, component_launcher_class, component_config, tfx_pipeline), *[beam.pvalue.AsIter(s) for s in signals_to_wait])
                    absl.logging.info('Component %s is scheduled.', component_id)


forward

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

Class description:
area under the precision-recall curve loss, Reference: "Scalable Learning of Non-Decomposable Objectives", Section 5 TensorFlow Implementation: https://github.com/tensorflow/models/tree/master/research/global_objectives

Method signatures and docstrings:
- def __init__(self, num_classes=1, num_anchors=20): Args: config: Config containing `precision_range_lower`, `precision_range_upper`, `num_classes`, `num_anchors`
- def forward(self, logits, targets, reduce=True, size_average=True, weights=None): Args: logits: Variable :math:`(N, C)` where `C = number of classes` targets: Variable :math:`(N)` where each value is `0 <= targets[i] <= C-1` weights: Coefficients for the loss. Must be a `Tensor` of shape [N] or [N, C], where `N = batch_size`, `C = number of classes`. size_average (bool, optional): By default, the losses are averaged over observations for each minibatch. However, if the field sizeAverage is set to False, the losses are instead summed for each minibatch. Default: ``True`` reduce (bool, optional): By default, the losses are averaged or summed over observations for each minibatch depending on size_average. When reduce is False, returns a loss per input/target element instead
- def _prepare_labels_weights(logits, targets, weights=None): Args: logits: Variable :math:`(N, C)` where `C = number of classes` targets: Variable :math:`(N)` where each value is `0 <= targets[i] <= C-1` weights: Coefficients for the loss. Must be a `Tensor` of shape [N] or [N, C], where `N = batch_size`, `C = number of classes`. Returns: labels: Tensor of shape [N, C], one-hot representation weights: Tensor of shape broadcastable to labels

Implement the Python class `AUCPRHingeLoss` described below.

Class description:
area under the precision-recall curve loss, Reference: "Scalable Learning of Non-Decomposable Objectives", Section 5 TensorFlow Implementation: https://github.com/tensorflow/models/tree/master/research/global_objectives

Method signatures and docstrings:
- def __init__(self, num_classes=1, num_anchors=20): Args: config: Config containing `precision_range_lower`, `precision_range_upper`, `num_classes`, `num_anchors`
- def forward(self, logits, targets, reduce=True, size_average=True, weights=None): Args: logits: Variable :math:`(N, C)` where `C = number of classes` targets: Variable :math:`(N)` where each value is `0 <= targets[i] <= C-1` weights: Coefficients for the loss. Must be a `Tensor` of shape [N] or [N, C], where `N = batch_size`, `C = number of classes`. size_average (bool, optional): By default, the losses are averaged over observations for each minibatch. However, if the field sizeAverage is set to False, the losses are instead summed for each minibatch. Default: ``True`` reduce (bool, optional): By default, the losses are averaged or summed over observations for each minibatch depending on size_average. When reduce is False, returns a loss per input/target element instead
- def _prepare_labels_weights(logits, targets, weights=None): Args: logits: Variable :math:`(N, C)` where `C = number of classes` targets: Variable :math:`(N)` where each value is `0 <= targets[i] <= C-1` weights: Coefficients for the loss. Must be a `Tensor` of shape [N] or [N, C], where `N = batch_size`, `C = number of classes`. Returns: labels: Tensor of shape [N, C], one-hot representation weights: Tensor of shape broadcastable to labels

<|skeleton|>
class AUCPRHingeLoss:
    """area under the precision-recall curve loss, Reference: "Scalable Learning of Non-Decomposable Objectives", Section 5 TensorFlow Implementation: https://github.com/tensorflow/models/tree/master/research/global_objectives"""

    def __init__(self, num_classes=1, num_anchors=20):
        """Args: config: Config containing `precision_range_lower`, `precision_range_upper`, `num_classes`, `num_anchors`"""
        <|body_0|>

    def forward(self, logits, targets, reduce=True, size_average=True, weights=None):
        """Args: logits: Variable :math:`(N, C)` where `C = number of classes` targets: Variable :math:`(N)` where each value is `0 <= targets[i] <= C-1` weights: Coefficients for the loss. Must be a `Tensor` of shape [N] or [N, C], where `N = batch_size`, `C = number of classes`. size_average (bool, optional): By default, the losses are averaged over observations for each minibatch. However, if the field sizeAverage is set to False, the losses are instead summed for each minibatch. Default: ``True`` reduce (bool, optional): By default, the losses are averaged or summed over observations for each minibatch depending on size_average. When reduce is False, returns a loss per input/target element instead"""
        <|body_1|>

    def _prepare_labels_weights(logits, targets, weights=None):
        """Args: logits: Variable :math:`(N, C)` where `C = number of classes` targets: Variable :math:`(N)` where each value is `0 <= targets[i] <= C-1` weights: Coefficients for the loss. Must be a `Tensor` of shape [N] or [N, C], where `N = batch_size`, `C = number of classes`. Returns: labels: Tensor of shape [N, C], one-hot representation weights: Tensor of shape broadcastable to labels"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        super().__init__()
        precision_range_lower = 0.0
        precision_range_upper = 1.0
        self.num_classes = num_classes
        self.num_anchors = num_anchors
        self.precision_range = (precision_range_lower, precision_range_upper)
        precision_values, self.delta = range_to_anchors_and_delta(self.precision_range, self.num_anchors)
        self.register_buffer('precision_values', precision_values)
        self.biases = nn.Parameter(torch.zeros(self.num_classes, self.num_anchors, dtype=torch.float))
        self.lambdas = nn.Parameter(torch.ones(self.num_classes, self.num_anchors, dtype=torch.float))
<|end_body_0|>

<|body_start_1|>
        targets = targets['target']
        C = 1 if logits.dim() == 1 else logits.size(1)
        if self.num_classes != C:
            raise ValueError('num classes is %d while logits width is %d' % (self.num_classes, C))
        labels, weights = AUCPRHingeLoss._prepare_labels_weights(logits, targets, weights=weights)
        lambdas = lagrange_multiplier(self.lambdas)
        hinge_loss = weighted_hinge_loss(labels.unsqueeze(-1), logits.unsqueeze(-1) - self.biases, positive_weights=1.0 + lambdas * (1.0 - self.precision_values), negative_weights=lambdas * self.precision_values)
        class_priors = build_class_priors(labels, weights=weights)
        lambda_term = class_priors.unsqueeze(-1) * (lambdas * (1.0 - self.precision_values))
        per_anchor_loss = weights.unsqueeze(-1) * hinge_loss - lambda_term
        loss = per_anchor_loss.sum(2) * self.delta
        loss = loss / (self.precision_range[1] - self.precision_range[0])
        if not reduce:
            return loss
        elif size_average:
            return loss.mean()
        else:
            return loss.sum()
<|end_body_1|>

<|body_start_2|>
        N, C = logits.size()
        labels = torch.zeros((N, C), dtype=torch.float, device=logits.device).scatter(1, targets.unsqueeze(1), 1)
        if weights is None:
            weights = torch.ones(N, dtype=torch.float, device=logits.device)
        if weights.dim() == 1:
            weights.unsqueeze_(-1)
        return (labels, weights)
<|end_body_2|>

Solution:
class AUCPRHingeLoss:
    """area under the precision-recall curve loss, Reference: "Scalable Learning of Non-Decomposable Objectives", Section 5 TensorFlow Implementation: https://github.com/tensorflow/models/tree/master/research/global_objectives"""

    def __init__(self, num_classes=1, num_anchors=20):
        """Args: config: Config containing `precision_range_lower`, `precision_range_upper`, `num_classes`, `num_anchors`"""
        super().__init__()
        precision_range_lower = 0.0
        precision_range_upper = 1.0
        self.num_classes = num_classes
        self.num_anchors = num_anchors
        self.precision_range = (precision_range_lower, precision_range_upper)
        precision_values, self.delta = range_to_anchors_and_delta(self.precision_range, self.num_anchors)
        self.register_buffer('precision_values', precision_values)
        self.biases = nn.Parameter(torch.zeros(self.num_classes, self.num_anchors, dtype=torch.float))
        self.lambdas = nn.Parameter(torch.ones(self.num_classes, self.num_anchors, dtype=torch.float))

    def forward(self, logits, targets, reduce=True, size_average=True, weights=None):
        """Args: logits: Variable :math:`(N, C)` where `C = number of classes` targets: Variable :math:`(N)` where each value is `0 <= targets[i] <= C-1` weights: Coefficients for the loss. Must be a `Tensor` of shape [N] or [N, C], where `N = batch_size`, `C = number of classes`. size_average (bool, optional): By default, the losses are averaged over observations for each minibatch. However, if the field sizeAverage is set to False, the losses are instead summed for each minibatch. Default: ``True`` reduce (bool, optional): By default, the losses are averaged or summed over observations for each minibatch depending on size_average. When reduce is False, returns a loss per input/target element instead"""
        targets = targets['target']
        C = 1 if logits.dim() == 1 else logits.size(1)
        if self.num_classes != C:
            raise ValueError('num classes is %d while logits width is %d' % (self.num_classes, C))
        labels, weights = AUCPRHingeLoss._prepare_labels_weights(logits, targets, weights=weights)
        lambdas = lagrange_multiplier(self.lambdas)
        hinge_loss = weighted_hinge_loss(labels.unsqueeze(-1), logits.unsqueeze(-1) - self.biases, positive_weights=1.0 + lambdas * (1.0 - self.precision_values), negative_weights=lambdas * self.precision_values)
        class_priors = build_class_priors(labels, weights=weights)
        lambda_term = class_priors.unsqueeze(-1) * (lambdas * (1.0 - self.precision_values))
        per_anchor_loss = weights.unsqueeze(-1) * hinge_loss - lambda_term
        loss = per_anchor_loss.sum(2) * self.delta
        loss = loss / (self.precision_range[1] - self.precision_range[0])
        if not reduce:
            return loss
        elif size_average:
            return loss.mean()
        else:
            return loss.sum()

    def _prepare_labels_weights(logits, targets, weights=None):
        """Args: logits: Variable :math:`(N, C)` where `C = number of classes` targets: Variable :math:`(N)` where each value is `0 <= targets[i] <= C-1` weights: Coefficients for the loss. Must be a `Tensor` of shape [N] or [N, C], where `N = batch_size`, `C = number of classes`. Returns: labels: Tensor of shape [N, C], one-hot representation weights: Tensor of shape broadcastable to labels"""
        N, C = logits.size()
        labels = torch.zeros((N, C), dtype=torch.float, device=logits.device).scatter(1, targets.unsqueeze(1), 1)
        if weights is None:
            weights = torch.ones(N, dtype=torch.float, device=logits.device)
        if weights.dim() == 1:
            weights.unsqueeze_(-1)
        return (labels, weights)


updateWidget

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

Class description:
This class is used for the methods needed for presenting the StdPrm

Method signatures and docstrings:
- def widgets(std_prm: Parameter) -> List[QWidget]: - This method generates all needed for input to the std_prm - A QLineEdit for the std_prm name - An input widget for the std_prm (by activating the "build_method" attribute of the parameters) Args: std_prm : (Parameter) - The parameter to be presented
- def updateWidget(parameter: Parameter): Update the widget of the parameter with the value. The following is the process of the update: - The widget is changed - The widget change activates a slot - The slot changes the Parameter value - This method is used to change the widget

Implement the Python class `StdPrmInput` described below.

Class description:
This class is used for the methods needed for presenting the StdPrm

Method signatures and docstrings:
- def widgets(std_prm: Parameter) -> List[QWidget]: - This method generates all needed for input to the std_prm - A QLineEdit for the std_prm name - An input widget for the std_prm (by activating the "build_method" attribute of the parameters) Args: std_prm : (Parameter) - The parameter to be presented
- def updateWidget(parameter: Parameter): Update the widget of the parameter with the value. The following is the process of the update: - The widget is changed - The widget change activates a slot - The slot changes the Parameter value - This method is used to change the widget

<|skeleton|>
class StdPrmInput:
    """This class is used for the methods needed for presenting the StdPrm"""

    def widgets(std_prm: Parameter) -> List[QWidget]:
        """- This method generates all needed for input to the std_prm - A QLineEdit for the std_prm name - An input widget for the std_prm (by activating the "build_method" attribute of the parameters) Args: std_prm : (Parameter) - The parameter to be presented"""
        <|body_0|>

    def updateWidget(parameter: Parameter):
        """Update the widget of the parameter with the value. The following is the process of the update: - The widget is changed - The widget change activates a slot - The slot changes the Parameter value - This method is used to change the widget"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        widgets = []
        textEdit = QLineEdit()
        textEdit.setText(std_prm['name'])
        widgets.append(textEdit)
        inputWidget = std_prm['build method'](std_prm['build method prms'], std_prm['slot'])
        widgets.append(inputWidget)
        std_prm['name widget'] = textEdit
        std_prm['widget'] = inputWidget
        return widgets
<|end_body_0|>

<|body_start_1|>
        if isinstance(parameter['widget'], QPushButton):
            parameter['widget'].setText(parameter['value'])
        elif isinstance(parameter['widget'], QComboBox):
            parameter['widget'].currentTextChanged.disconnect()
            parameter['widget'].setCurrentText(parameter['value'])
            parameter['widget'].currentTextChanged.connect(parameter['slot'])
<|end_body_1|>

Solution:
class StdPrmInput:
    """This class is used for the methods needed for presenting the StdPrm"""

    def widgets(std_prm: Parameter) -> List[QWidget]:
        """- This method generates all needed for input to the std_prm - A QLineEdit for the std_prm name - An input widget for the std_prm (by activating the "build_method" attribute of the parameters) Args: std_prm : (Parameter) - The parameter to be presented"""
        widgets = []
        textEdit = QLineEdit()
        textEdit.setText(std_prm['name'])
        widgets.append(textEdit)
        inputWidget = std_prm['build method'](std_prm['build method prms'], std_prm['slot'])
        widgets.append(inputWidget)
        std_prm['name widget'] = textEdit
        std_prm['widget'] = inputWidget
        return widgets

    def updateWidget(parameter: Parameter):
        """Update the widget of the parameter with the value. The following is the process of the update: - The widget is changed - The widget change activates a slot - The slot changes the Parameter value - This method is used to change the widget"""
        if isinstance(parameter['widget'], QPushButton):
            parameter['widget'].setText(parameter['value'])
        elif isinstance(parameter['widget'], QComboBox):
            parameter['widget'].currentTextChanged.disconnect()
            parameter['widget'].setCurrentText(parameter['value'])
            parameter['widget'].currentTextChanged.connect(parameter['slot'])


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

Class description:
Implement the Direction class.

Method signatures and docstrings:
- def format_direction(cls, direction): :param direction: 朝向 :return: 有效朝向
- def update_direction(cls, city, region, name, house_num, direction, direction_source, room_num=None): :param city: 城市 :param region: 区域 :param name: 小区名 :param house_num: 楼栋号 :param direction: 朝向 :param direction_source: 朝向来源 :param room_num: 房号

Implement the Python class `Direction` described below.

Class description:
Implement the Direction class.

Method signatures and docstrings:
- def format_direction(cls, direction): :param direction: 朝向 :return: 有效朝向
- def update_direction(cls, city, region, name, house_num, direction, direction_source, room_num=None): :param city: 城市 :param region: 区域 :param name: 小区名 :param house_num: 楼栋号 :param direction: 朝向 :param direction_source: 朝向来源 :param room_num: 房号

<|skeleton|>
class Direction:

    def format_direction(cls, direction):
        """:param direction: 朝向 :return: 有效朝向"""
        <|body_0|>

    def update_direction(cls, city, region, name, house_num, direction, direction_source, room_num=None):
        """:param city: 城市 :param region: 区域 :param name: 小区名 :param house_num: 楼栋号 :param direction: 朝向 :param direction_source: 朝向来源 :param room_num: 房号"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        word_list = []
        for k in ['东', '南', '西', '北']:
            if k in str(direction):
                word_list.append(k)
        if len(word_list) > 0 and ''.join(word_list) in cls._true_words:
            return ''.join(word_list)
<|end_body_0|>

<|body_start_1|>
        query = {'city': city, 'region': region, 'name': name, 'house_num': house_num}
        if room_num:
            query = {'city': city, 'region': region, 'name': name, 'house_num': house_num, 'room_num': room_num}
        direction = cls.format_direction(direction)
        if direction:
            house_list = list(update_col.find(query))
            if len(house_list) > 0:
                print(query, '***更新')
                for house in house_list:
                    if 'direction' not in house or house['direction'] not in cls._true_words:
                        columns_source = []
                        try:
                            columns_source = house['columns_source']
                        except:
                            pass
                        if house.get('from', None) != direction_source:
                            if len(columns_source) > 0:
                                for column in columns_source:
                                    if 'direction' in column:
                                        columns_source.remove(column)
                            columns_source.append({'direction': '小资家', 'u_time': datetime.utcnow()})
                        update_col.update_one({'_id': house['_id']}, {'$set': {'direction': direction, 'columns_source': columns_source, 'm_date': datetime.utcnow()}})
<|end_body_1|>

Solution:
class Direction:
    def format_direction(cls, direction):
        """:param direction: 朝向 :return: 有效朝向"""
        word_list = []
        for k in ['东', '南', '西', '北']:
            if k in str(direction):
                word_list.append(k)
        if len(word_list) > 0 and ''.join(word_list) in cls._true_words:
            return ''.join(word_list)

    def update_direction(cls, city, region, name, house_num, direction, direction_source, room_num=None):
        """:param city: 城市 :param region: 区域 :param name: 小区名 :param house_num: 楼栋号 :param direction: 朝向 :param direction_source: 朝向来源 :param room_num: 房号"""
        query = {'city': city, 'region': region, 'name': name, 'house_num': house_num}
        if room_num:
            query = {'city': city, 'region': region, 'name': name, 'house_num': house_num, 'room_num': room_num}
        direction = cls.format_direction(direction)
        if direction:
            house_list = list(update_col.find(query))
            if len(house_list) > 0:
                print(query, '***更新')
                for house in house_list:
                    if 'direction' not in house or house['direction'] not in cls._true_words:
                        columns_source = []
                        try:
                            columns_source = house['columns_source']
                        except:
                            pass
                        if house.get('from', None) != direction_source:
                            if len(columns_source) > 0:
                                for column in columns_source:
                                    if 'direction' in column:
                                        columns_source.remove(column)
                            columns_source.append({'direction': '小资家', 'u_time': datetime.utcnow()})
                        update_col.update_one({'_id': house['_id']}, {'$set': {'direction': direction, 'columns_source': columns_source, 'm_date': datetime.utcnow()}})