cleanup

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

Class description:
Configure boot device to bios, pxe, hdd, cdrom, floppy drive options in non persistent mode when boot device set from 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 non-persistent mode
- def cleanup(self, cimc_util_obj, config): Test Case Cleanup

Implement the Python class `CimcConfigIPMICmdNonPersistentBootDevice` described below.

Class description:
Configure boot device to bios, pxe, hdd, cdrom, floppy drive options in non persistent mode when boot device set from 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 non-persistent mode
- def cleanup(self, cimc_util_obj, config): Test Case Cleanup

<|skeleton|>
class CimcConfigIPMICmdNonPersistentBootDevice:
    """Configure boot device to bios, pxe, hdd, cdrom, floppy drive options in non persistent mode when boot device set from 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 non-persistent mode"""
        <|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:
            log.error('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('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 non-persistent boot for boot device %s' % parameter)
<|end_body_1|>

<|body_start_2|>
        expected_out = classparam['expected_out']
        validation_string = classparam['validation_string']
        self.host_serial_handle.disconnect()
        remove_consistent_ipmi_boot(cimc_util_obj, config)
        log.info('Cleanup section passed')
<|end_body_2|>

Solution:
class CimcConfigIPMICmdNonPersistentBootDevice:
    """Configure boot device to bios, pxe, hdd, cdrom, floppy drive options in non persistent mode when boot device set from 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:
            log.error('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 non-persistent mode"""
        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('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 non-persistent boot for boot device %s' % parameter)

    def cleanup(self, cimc_util_obj, config):
        """Test Case Cleanup"""
        expected_out = classparam['expected_out']
        validation_string = classparam['validation_string']
        self.host_serial_handle.disconnect()
        remove_consistent_ipmi_boot(cimc_util_obj, config)
        log.info('Cleanup section passed')


execute

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

Class description:
_LoadFromID_ Retrieve meta data for a job given it's ID. This includes the name, job group and last update time.

Method signatures and docstrings:
- def formatDict(self, result): _formatDict_ Cast the id, jobgroup and last_update columns to integers because formatDict() turns everything into strings.
- def execute(self, jobID, conn=None, transaction=False): _execute_ Execute the SQL for the given job ID and then format and return the result.

Implement the Python class `LoadFromID` described below.

Class description:
_LoadFromID_ Retrieve meta data for a job given it's ID. This includes the name, job group and last update time.

Method signatures and docstrings:
- def formatDict(self, result): _formatDict_ Cast the id, jobgroup and last_update columns to integers because formatDict() turns everything into strings.
- def execute(self, jobID, conn=None, transaction=False): _execute_ Execute the SQL for the given job ID and then format and return the result.

<|skeleton|>
class LoadFromID:
    """_LoadFromID_ Retrieve meta data for a job given it's ID. This includes the name, job group and last update time."""

    def formatDict(self, result):
        """_formatDict_ Cast the id, jobgroup and last_update columns to integers because formatDict() turns everything into strings."""
        <|body_0|>

    def execute(self, jobID, conn=None, transaction=False):
        """_execute_ Execute the SQL for the given job ID and then format and return the result."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        formattedResult = DBFormatter.formatDict(self, result)
        for entry in formattedResult:
            if entry['bool_outcome'] == 0:
                entry['outcome'] = 'failure'
            else:
                entry['outcome'] = 'success'
            del entry['bool_outcome']
        if len(formattedResult) == 1:
            return formattedResult[0]
        else:
            return formattedResult
<|end_body_0|>

<|body_start_1|>
        if isinstance(jobID, list):
            binds = jobID
        else:
            binds = {'jobid': jobID}
        result = self.dbi.processData(self.sql, binds, conn=conn, transaction=transaction)
        return self.formatDict(result)
<|end_body_1|>

Solution:
class LoadFromID:
    """_LoadFromID_ Retrieve meta data for a job given it's ID. This includes the name, job group and last update time."""

    def formatDict(self, result):
        """_formatDict_ Cast the id, jobgroup and last_update columns to integers because formatDict() turns everything into strings."""
        formattedResult = DBFormatter.formatDict(self, result)
        for entry in formattedResult:
            if entry['bool_outcome'] == 0:
                entry['outcome'] = 'failure'
            else:
                entry['outcome'] = 'success'
            del entry['bool_outcome']
        if len(formattedResult) == 1:
            return formattedResult[0]
        else:
            return formattedResult

    def execute(self, jobID, conn=None, transaction=False):
        """_execute_ Execute the SQL for the given job ID and then format and return the result."""
        if isinstance(jobID, list):
            binds = jobID
        else:
            binds = {'jobid': jobID}
        result = self.dbi.processData(self.sql, binds, conn=conn, transaction=transaction)
        return self.formatDict(result)


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

Class description:
Implement the SIFT_Obj class.

Method signatures and docstrings:
- def __init__(self, img, nOctaveLayers=3, contrastThreshold=0.04, edgeThreshold=10, sigma=1.6): **Definition**: SIFT_Obj(img, upright = False) SIFT object class. Implementation of SIFT detector and SIFT descriptor. **Inputs**: * img: the source image for which the descriptors are computed * nOctaveLayers (optional): default *3*. See OpenCV documentation * contrastThreshold (optional): default *0.04*. See OpenCV documentation * edgeThreshold (optional): default *10*. See OpenCV documentation * sigma (optional): default *1.6*. See OpenCV documentation **Outputs - Class members**: * keyPoints: extracted SIFT keypoints for the image *img*. Type: KeyPoint class of OpenCV. * descriptors: extracted SIFT descriptors for image *img*. Type: numpy array of dimensions *number_of_keypoints x 128*.
- def SIFT_Keypoints_Descriptors(self, plot_flag=True): **Definition**: SIFT_Keypoints_Descriptors(plot_flag = True) Implements keypoint detection and descriptors computation. Detected keypoints are stored in **self.keyPoints** and computed descriptors are stored in **self.descriptors**. Additionally, it extracts keypoints coordinates. Coordinates are stored in **self.coordinates**. **Inputs**: * plot_flag (optional): default *True*. If *True* this method plots keypoints on source image *img*. **Outputs**: * *None*

Implement the Python class `SIFT_Obj` described below.

Class description:
Implement the SIFT_Obj class.

Method signatures and docstrings:
- def __init__(self, img, nOctaveLayers=3, contrastThreshold=0.04, edgeThreshold=10, sigma=1.6): **Definition**: SIFT_Obj(img, upright = False) SIFT object class. Implementation of SIFT detector and SIFT descriptor. **Inputs**: * img: the source image for which the descriptors are computed * nOctaveLayers (optional): default *3*. See OpenCV documentation * contrastThreshold (optional): default *0.04*. See OpenCV documentation * edgeThreshold (optional): default *10*. See OpenCV documentation * sigma (optional): default *1.6*. See OpenCV documentation **Outputs - Class members**: * keyPoints: extracted SIFT keypoints for the image *img*. Type: KeyPoint class of OpenCV. * descriptors: extracted SIFT descriptors for image *img*. Type: numpy array of dimensions *number_of_keypoints x 128*.
- def SIFT_Keypoints_Descriptors(self, plot_flag=True): **Definition**: SIFT_Keypoints_Descriptors(plot_flag = True) Implements keypoint detection and descriptors computation. Detected keypoints are stored in **self.keyPoints** and computed descriptors are stored in **self.descriptors**. Additionally, it extracts keypoints coordinates. Coordinates are stored in **self.coordinates**. **Inputs**: * plot_flag (optional): default *True*. If *True* this method plots keypoints on source image *img*. **Outputs**: * *None*

<|skeleton|>
class SIFT_Obj:

    def __init__(self, img, nOctaveLayers=3, contrastThreshold=0.04, edgeThreshold=10, sigma=1.6):
        """**Definition**: SIFT_Obj(img, upright = False) SIFT object class. Implementation of SIFT detector and SIFT descriptor. **Inputs**: * img: the source image for which the descriptors are computed * nOctaveLayers (optional): default *3*. See OpenCV documentation * contrastThreshold (optional): default *0.04*. See OpenCV documentation * edgeThreshold (optional): default *10*. See OpenCV documentation * sigma (optional): default *1.6*. See OpenCV documentation **Outputs - Class members**: * keyPoints: extracted SIFT keypoints for the image *img*. Type: KeyPoint class of OpenCV. * descriptors: extracted SIFT descriptors for image *img*. Type: numpy array of dimensions *number_of_keypoints x 128*."""
        <|body_0|>

    def SIFT_Keypoints_Descriptors(self, plot_flag=True):
        """**Definition**: SIFT_Keypoints_Descriptors(plot_flag = True) Implements keypoint detection and descriptors computation. Detected keypoints are stored in **self.keyPoints** and computed descriptors are stored in **self.descriptors**. Additionally, it extracts keypoints coordinates. Coordinates are stored in **self.coordinates**. **Inputs**: * plot_flag (optional): default *True*. If *True* this method plots keypoints on source image *img*. **Outputs**: * *None*"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.input = img
        self.siftDetector = cv2.FeatureDetector_create('SIFT')
        self.siftDetector.setInt('nOctaveLayers', nOctaveLayers)
        self.siftDetector.setDouble('contrastThreshold', contrastThreshold)
        self.siftDetector.setInt('edgeThreshold', edgeThreshold)
        self.siftDetector.setDouble('sigma', sigma)
        self.siftExtractor = cv2.DescriptorExtractor_create('SIFT')
        self.keyPoints = None
        self.descriptors = None
        self.coordinates = None
<|end_body_0|>

<|body_start_1|>
        keyPoints = self.siftDetector.detect(self.input, None)
        keyPoints, descriptors = self.siftExtractor.compute(self.input, keyPoints)
        self.keyPoints = keyPoints
        self.descriptors = descriptors
        m = size(self.keyPoints)
        siftCoord = np.zeros([m, 2])
        for i in range(m):
            siftCoord[i][0] = self.keyPoints[i].pt[1]
            siftCoord[i][1] = self.keyPoints[i].pt[0]
        if plot_flag == True:
            figure()
            gray()
            imshow(self.input)
            plot([p[1] for p in siftCoord], [p[0] for p in siftCoord], '*')
            axis('off')
            show()
        self.coordinates = siftCoord
<|end_body_1|>

Solution:
class SIFT_Obj:
    def __init__(self, img, nOctaveLayers=3, contrastThreshold=0.04, edgeThreshold=10, sigma=1.6):
        """**Definition**: SIFT_Obj(img, upright = False) SIFT object class. Implementation of SIFT detector and SIFT descriptor. **Inputs**: * img: the source image for which the descriptors are computed * nOctaveLayers (optional): default *3*. See OpenCV documentation * contrastThreshold (optional): default *0.04*. See OpenCV documentation * edgeThreshold (optional): default *10*. See OpenCV documentation * sigma (optional): default *1.6*. See OpenCV documentation **Outputs - Class members**: * keyPoints: extracted SIFT keypoints for the image *img*. Type: KeyPoint class of OpenCV. * descriptors: extracted SIFT descriptors for image *img*. Type: numpy array of dimensions *number_of_keypoints x 128*."""
        self.input = img
        self.siftDetector = cv2.FeatureDetector_create('SIFT')
        self.siftDetector.setInt('nOctaveLayers', nOctaveLayers)
        self.siftDetector.setDouble('contrastThreshold', contrastThreshold)
        self.siftDetector.setInt('edgeThreshold', edgeThreshold)
        self.siftDetector.setDouble('sigma', sigma)
        self.siftExtractor = cv2.DescriptorExtractor_create('SIFT')
        self.keyPoints = None
        self.descriptors = None
        self.coordinates = None

    def SIFT_Keypoints_Descriptors(self, plot_flag=True):
        """**Definition**: SIFT_Keypoints_Descriptors(plot_flag = True) Implements keypoint detection and descriptors computation. Detected keypoints are stored in **self.keyPoints** and computed descriptors are stored in **self.descriptors**. Additionally, it extracts keypoints coordinates. Coordinates are stored in **self.coordinates**. **Inputs**: * plot_flag (optional): default *True*. If *True* this method plots keypoints on source image *img*. **Outputs**: * *None*"""
        keyPoints = self.siftDetector.detect(self.input, None)
        keyPoints, descriptors = self.siftExtractor.compute(self.input, keyPoints)
        self.keyPoints = keyPoints
        self.descriptors = descriptors
        m = size(self.keyPoints)
        siftCoord = np.zeros([m, 2])
        for i in range(m):
            siftCoord[i][0] = self.keyPoints[i].pt[1]
            siftCoord[i][1] = self.keyPoints[i].pt[0]
        if plot_flag == True:
            figure()
            gray()
            imshow(self.input)
            plot([p[1] for p in siftCoord], [p[0] for p in siftCoord], '*')
            axis('off')
            show()
        self.coordinates = siftCoord


update

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

Class description:
Get the latest data from HDDTemp and update the states.

Method signatures and docstrings:
- def __init__(self, host, port): Initialize the data object.
- def update(self): Get the latest data from HDDTemp running as daemon.

Implement the Python class `HddTempData` described below.

Class description:
Get the latest data from HDDTemp and update the states.

Method signatures and docstrings:
- def __init__(self, host, port): Initialize the data object.
- def update(self): Get the latest data from HDDTemp running as daemon.

<|skeleton|>
class HddTempData:
    """Get the latest data from HDDTemp and update the states."""

    def __init__(self, host, port):
        """Initialize the data object."""
        <|body_0|>

    def update(self):
        """Get the latest data from HDDTemp running as daemon."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.host = host
        self.port = port
        self.data = None
<|end_body_0|>

<|body_start_1|>
        try:
            connection = Telnet(host=self.host, port=self.port, timeout=DEFAULT_TIMEOUT)
            data = connection.read_all().decode('ascii').lstrip('|').rstrip('|').split('||')
            self.data = {data[i].split('|')[0]: data[i] for i in range(0, len(data), 1)}
        except ConnectionRefusedError:
            _LOGGER.error('HDDTemp is not available at %s:%s', self.host, self.port)
            self.data = None
        except socket.gaierror:
            _LOGGER.error('HDDTemp host not found %s:%s', self.host, self.port)
            self.data = None
<|end_body_1|>

Solution:
class HddTempData:
    """Get the latest data from HDDTemp and update the states."""

    def __init__(self, host, port):
        """Initialize the data object."""
        self.host = host
        self.port = port
        self.data = None

    def update(self):
        """Get the latest data from HDDTemp running as daemon."""
        try:
            connection = Telnet(host=self.host, port=self.port, timeout=DEFAULT_TIMEOUT)
            data = connection.read_all().decode('ascii').lstrip('|').rstrip('|').split('||')
            self.data = {data[i].split('|')[0]: data[i] for i in range(0, len(data), 1)}
        except ConnectionRefusedError:
            _LOGGER.error('HDDTemp is not available at %s:%s', self.host, self.port)
            self.data = None
        except socket.gaierror:
            _LOGGER.error('HDDTemp host not found %s:%s', self.host, self.port)
            self.data = None


exist

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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def _dfs(self, board, used, row, col, word, i): row, col: search neighboring cells of [row][col] i: index of the character in word to be searched
- def exist(self, board, word): :type board: List[List[str]] :type word: str :rtype: bool

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def _dfs(self, board, used, row, col, word, i): row, col: search neighboring cells of [row][col] i: index of the character in word to be searched
- def exist(self, board, word): :type board: List[List[str]] :type word: str :rtype: bool

<|skeleton|>
class Solution:

    def _dfs(self, board, used, row, col, word, i):
        """row, col: search neighboring cells of [row][col] i: index of the character in word to be searched"""
        <|body_0|>

    def exist(self, board, word):
        """:type board: List[List[str]] :type word: str :rtype: bool"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        if i >= len(word):
            return True
        res = False
        neighbors = [(row - 1, col), (row, col + 1), (row + 1, col), (row, col - 1)]
        for index in neighbors:
            if -1 < index[0] < len(board) and -1 < index[1] < len(board[0]):
                if board[index[0]][index[1]] == word[i] and (not used[index[0]][index[1]]):
                    used[index[0]][index[1]] = True
                    res = res or self._dfs(board, used, index[0], index[1], word, i + 1)
                    used[index[0]][index[1]] = False
        return res
<|end_body_0|>

<|body_start_1|>
        if not board or not board[0]:
            if not word:
                return True
            else:
                return False
        elif not word:
            return False
        m, n = (len(board), len(board[0]))
        used = [[False for j in range(n)] for i in range(m)]
        res = False
        for i in range(m):
            for j in range(n):
                if board[i][j] == word[0]:
                    used[i][j] = True
                    res = res or self._dfs(board, used, i, j, word, 1)
                    used[i][j] = False
        return res
<|end_body_1|>

Solution:
class Solution:
    def _dfs(self, board, used, row, col, word, i):
        """row, col: search neighboring cells of [row][col] i: index of the character in word to be searched"""
        if i >= len(word):
            return True
        res = False
        neighbors = [(row - 1, col), (row, col + 1), (row + 1, col), (row, col - 1)]
        for index in neighbors:
            if -1 < index[0] < len(board) and -1 < index[1] < len(board[0]):
                if board[index[0]][index[1]] == word[i] and (not used[index[0]][index[1]]):
                    used[index[0]][index[1]] = True
                    res = res or self._dfs(board, used, index[0], index[1], word, i + 1)
                    used[index[0]][index[1]] = False
        return res

    def exist(self, board, word):
        """:type board: List[List[str]] :type word: str :rtype: bool"""
        if not board or not board[0]:
            if not word:
                return True
            else:
                return False
        elif not word:
            return False
        m, n = (len(board), len(board[0]))
        used = [[False for j in range(n)] for i in range(m)]
        res = False
        for i in range(m):
            for j in range(n):
                if board[i][j] == word[0]:
                    used[i][j] = True
                    res = res or self._dfs(board, used, i, j, word, 1)
                    used[i][j] = False
        return res


deserialize

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

Class description:
Implement the Codec class.

Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.

Implement the Python class `Codec` described below.

Class description:
Implement the Codec class.

Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.

<|skeleton|>
class Codec:

    def serialize(self, root: TreeNode) -> str:
        """Encodes a tree to a single string."""
        <|body_0|>

    def deserialize(self, data: str) -> TreeNode:
        """Decodes your encoded data to tree."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        if not root:
            return ''
        result = []
        nodes = [root]
        while nodes:
            node = nodes.pop()
            result.append(str(node.val))
            if node.right:
                nodes.append(node.right)
            if node.left:
                nodes.append(node.left)
        return ' '.join(result)
<|end_body_0|>

<|body_start_1|>
        if not data:
            return None
        preorder = [int(val) for val in data.split()]
        root = TreeNode(preorder[0])
        s = [root]
        for i in range(1, len(preorder)):
            node = None
            while s and preorder[i] > s[-1].val:
                node = s.pop()
            if node:
                node.right = TreeNode(preorder[i])
                s.append(node.right)
            else:
                s[-1].left = TreeNode(preorder[i])
                s.append(s[-1].left)
        return root
<|end_body_1|>

Solution:
class Codec:
    def serialize(self, root: TreeNode) -> str:
        """Encodes a tree to a single string."""
        if not root:
            return ''
        result = []
        nodes = [root]
        while nodes:
            node = nodes.pop()
            result.append(str(node.val))
            if node.right:
                nodes.append(node.right)
            if node.left:
                nodes.append(node.left)
        return ' '.join(result)

    def deserialize(self, data: str) -> TreeNode:
        """Decodes your encoded data to tree."""
        if not data:
            return None
        preorder = [int(val) for val in data.split()]
        root = TreeNode(preorder[0])
        s = [root]
        for i in range(1, len(preorder)):
            node = None
            while s and preorder[i] > s[-1].val:
                node = s.pop()
            if node:
                node.right = TreeNode(preorder[i])
                s.append(node.right)
            else:
                s[-1].left = TreeNode(preorder[i])
                s.append(s[-1].left)
        return root

Leetcode/449. Serialize and Deserialize BST/solution2.py


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

Class description:
Class that helps deal with single coupon instances and things related to a single coupon.

Method signatures and docstrings:
- def build_tweet_message(coupon, add_url=False): Create Tweet (Twitter Status) for this coupon.
- def twitter_connect(coupon, message=None): Connect to Twitter then either update or return latest status.

Implement the Python class `TwitterService` described below.

Class description:
Class that helps deal with single coupon instances and things related to a single coupon.

Method signatures and docstrings:
- def build_tweet_message(coupon, add_url=False): Create Tweet (Twitter Status) for this coupon.
- def twitter_connect(coupon, message=None): Connect to Twitter then either update or return latest status.

<|skeleton|>
class TwitterService:
    """Class that helps deal with single coupon instances and things related to a single coupon."""

    def build_tweet_message(coupon, add_url=False):
        """Create Tweet (Twitter Status) for this coupon."""
        <|body_0|>

    def twitter_connect(coupon, message=None):
        """Connect to Twitter then either update or return latest status."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        site = coupon.get_site()
        try:
            twitter_account = TwitterAccount.objects.get(site=site)
            twitter_name = twitter_account.twitter_name
        except TwitterAccount.DoesNotExist:
            twitter_name = None
        qualifier = coupon.offer.qualifier
        if add_url and len(qualifier) > 31:
            qualifier = qualifier[:31] + '...'
        message = '%s %s - %s' % (coupon.offer.headline, qualifier, coupon.offer.business.short_business_name)
        if twitter_name:
            message += ' @%s.' % twitter_name
        if add_url:
            message += ' Go to: '
            long_url = 'http://%s%s' % (site.domain, reverse('view-single-coupon', kwargs={'slug': coupon.slug(), 'coupon_id': coupon.id}))
            message += shorten_url(long_url)
        LOG.info('build tweet message = %s ' % message)
        return message
<|end_body_0|>

<|body_start_1|>
        site = coupon.get_site()
        LOG.info('twitter_connect')
        try:
            twitter_account = TwitterAccount.objects.get(site=site)
        except TwitterAccount.DoesNotExist:
            return
        if twitter_account.consumer_key and twitter_account.consumer_secret and twitter_account.access_key and twitter_account.access_secret and (twitter_account.consumer_key != '') and (twitter_account.consumer_secret != '') and (twitter_account.access_key != '') and (twitter_account.access_secret != ''):
            try:
                api = twitter.Api(consumer_key=twitter_account.consumer_key, consumer_secret=twitter_account.consumer_secret, access_token_key=twitter_account.access_key, access_token_secret=twitter_account.access_secret)
                if message:
                    api.PostUpdate(message)
                    LOG.debug('Success: tweet coupon id: %s' % str(coupon.id))
                    return
                else:
                    LOG.debug('Returning status')
                    try:
                        statuses = api.GetUserTimeline(twitter_account.twitter_name)
                        status = str(statuses[0].text)
                    except ValueError:
                        status = None
                    return status
            except twitter.TwitterError:
                LOG.error('Twitter connect failed for this site: %s' % site)
        return
<|end_body_1|>

Solution:
class TwitterService:
    """Class that helps deal with single coupon instances and things related to a single coupon."""

    def build_tweet_message(coupon, add_url=False):
        """Create Tweet (Twitter Status) for this coupon."""
        site = coupon.get_site()
        try:
            twitter_account = TwitterAccount.objects.get(site=site)
            twitter_name = twitter_account.twitter_name
        except TwitterAccount.DoesNotExist:
            twitter_name = None
        qualifier = coupon.offer.qualifier
        if add_url and len(qualifier) > 31:
            qualifier = qualifier[:31] + '...'
        message = '%s %s - %s' % (coupon.offer.headline, qualifier, coupon.offer.business.short_business_name)
        if twitter_name:
            message += ' @%s.' % twitter_name
        if add_url:
            message += ' Go to: '
            long_url = 'http://%s%s' % (site.domain, reverse('view-single-coupon', kwargs={'slug': coupon.slug(), 'coupon_id': coupon.id}))
            message += shorten_url(long_url)
        LOG.info('build tweet message = %s ' % message)
        return message

    def twitter_connect(coupon, message=None):
        """Connect to Twitter then either update or return latest status."""
        site = coupon.get_site()
        LOG.info('twitter_connect')
        try:
            twitter_account = TwitterAccount.objects.get(site=site)
        except TwitterAccount.DoesNotExist:
            return
        if twitter_account.consumer_key and twitter_account.consumer_secret and twitter_account.access_key and twitter_account.access_secret and (twitter_account.consumer_key != '') and (twitter_account.consumer_secret != '') and (twitter_account.access_key != '') and (twitter_account.access_secret != ''):
            try:
                api = twitter.Api(consumer_key=twitter_account.consumer_key, consumer_secret=twitter_account.consumer_secret, access_token_key=twitter_account.access_key, access_token_secret=twitter_account.access_secret)
                if message:
                    api.PostUpdate(message)
                    LOG.debug('Success: tweet coupon id: %s' % str(coupon.id))
                    return
                else:
                    LOG.debug('Returning status')
                    try:
                        statuses = api.GetUserTimeline(twitter_account.twitter_name)
                        status = str(statuses[0].text)
                    except ValueError:
                        status = None
                    return status
            except twitter.TwitterError:
                LOG.error('Twitter connect failed for this site: %s' % site)
        return


findMinHeightTrees

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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]: Brute Force, Time: O(V^2), Space: O(V)
- def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]: BFS, Time: O(V), Space: O(V)

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]: Brute Force, Time: O(V^2), Space: O(V)
- def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]: BFS, Time: O(V), Space: O(V)

<|skeleton|>
class Solution:

    def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
        """Brute Force, Time: O(V^2), Space: O(V)"""
        <|body_0|>

    def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
        """BFS, Time: O(V), Space: O(V)"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        """
                    Treat each node as root, calculate their depths, return the minimum roots.
                    This method will get TLE
                """
        graph = [[] for _ in range(n)]
        for a, b in edges:
            graph[a].append(b)
            graph[b].append(a)

        def get_height(root, visited):
            visited.add(root)
            height = 0
            for adj in graph[root]:
                if adj not in visited:
                    height = max(height, get_height(adj, visited))
            return height + 1
        min_height = float('+inf')
        heights = [0] * n
        for root in range(n):
            height = get_height(root, set())
            heights[root] = height
            min_height = min(min_height, height)
        return [node for node, height in enumerate(heights) if height == min_height]
<|end_body_0|>

<|body_start_1|>
        from collections import deque
        if n <= 2:
            return [i for i in range(n)]
        graph = [[] for _ in range(n)]
        for a, b in edges:
            graph[a].append(b)
            graph[b].append(a)
        q = deque()
        for node in range(n):
            if len(graph[node]) == 1:
                q.append(node)
        num_remain_node = n
        while num_remain_node > 2:
            sz = len(q)
            for _ in range(sz):
                node = q.popleft()
                for adj in graph[node]:
                    graph[adj].remove(node)
                    if len(graph[adj]) == 1:
                        q.append(adj)
                num_remain_node -= 1
        return [node for node in q]
<|end_body_1|>

Solution:
class Solution:
    def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
        """Brute Force, Time: O(V^2), Space: O(V)"""
        """
                    Treat each node as root, calculate their depths, return the minimum roots.
                    This method will get TLE
                """
        graph = [[] for _ in range(n)]
        for a, b in edges:
            graph[a].append(b)
            graph[b].append(a)

        def get_height(root, visited):
            visited.add(root)
            height = 0
            for adj in graph[root]:
                if adj not in visited:
                    height = max(height, get_height(adj, visited))
            return height + 1
        min_height = float('+inf')
        heights = [0] * n
        for root in range(n):
            height = get_height(root, set())
            heights[root] = height
            min_height = min(min_height, height)
        return [node for node, height in enumerate(heights) if height == min_height]

    def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
        """BFS, Time: O(V), Space: O(V)"""
        from collections import deque
        if n <= 2:
            return [i for i in range(n)]
        graph = [[] for _ in range(n)]
        for a, b in edges:
            graph[a].append(b)
            graph[b].append(a)
        q = deque()
        for node in range(n):
            if len(graph[node]) == 1:
                q.append(node)
        num_remain_node = n
        while num_remain_node > 2:
            sz = len(q)
            for _ in range(sz):
                node = q.popleft()
                for adj in graph[node]:
                    graph[adj].remove(node)
                    if len(graph[adj]) == 1:
                        q.append(adj)
                num_remain_node -= 1
        return [node for node in q]


hasGroupsSizeX

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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def hasGroupsSizeX(self, deck: List[int]) -> bool: gcd of all > 2
- def gcd(self, a, b): a = k * b + r gcd(a, b) = gcd(b, r)

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def hasGroupsSizeX(self, deck: List[int]) -> bool: gcd of all > 2
- def gcd(self, a, b): a = k * b + r gcd(a, b) = gcd(b, r)

<|skeleton|>
class Solution:

    def hasGroupsSizeX(self, deck: List[int]) -> bool:
        """gcd of all > 2"""
        <|body_0|>

    def gcd(self, a, b):
        """a = k * b + r gcd(a, b) = gcd(b, r)"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        counter = Counter(deck)
        gcd = None
        for v in counter.values():
            if gcd is None:
                gcd = v
            gcd = self.gcd(gcd, v)
            if gcd == 1:
                return False
        return True
<|end_body_0|>

<|body_start_1|>
        while b:
            a, b = (b, a % b)
        return a
<|end_body_1|>

Solution:
class Solution:
    def hasGroupsSizeX(self, deck: List[int]) -> bool:
        """gcd of all > 2"""
        counter = Counter(deck)
        gcd = None
        for v in counter.values():
            if gcd is None:
                gcd = v
            gcd = self.gcd(gcd, v)
            if gcd == 1:
                return False
        return True

    def gcd(self, a, b):
        """a = k * b + r gcd(a, b) = gcd(b, r)"""
        while b:
            a, b = (b, a % b)
        return a

_algorithms_challenges/leetcode/LeetCode/914 X of a Kind in a Deck of Cards.py


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

Class description:
Mixin to add datacenter related methods to the GraphQL client

Method signatures and docstrings:
- def get_datacenters(self, page: PageInput=None, dc_filter: DataCenterFilter=None, sort: DataCenterSort=None) -> DataCenterList: Retrieves a list of datacenter objects :param page: The requested page from the server. This is an optional argument and if omitted the server will default to returning the first page with a maximum of ``100`` items. :type page: PageInput, optional :param dc_filter: A filter object to filter the datacenters on the server. If omitted, the server will return all objects as a paginated response. :type dc_filter: DataCenterFilter, optional :param sort: A sort definition object to sort the datacenter objects on supported properties. If omitted objects are returned in the order as they were created in. :type sort: DataCenterSort, optional :returns DataCenterList: A paginated list of datacenters. :
- def create_datacenter(self, create_input: CreateDataCenterInput=None) -> DataCenter: Allows creation of a new datacenter object A datacenter record allows customers to logically organize their infrastructure by physical location and associate address and contact information with the physical location. This is useful for effective support case handling and reporting purposes. :param create_input: A property definition for the new datacenter :type create_input: CreateDataCenterInput :returns DataCenter: The new datacenter. :raises GraphQLError: An error with the GraphQL endpoint.
- def delete_datacenter(self, uuid: str, delete_input: DeleteDataCenterInput=None) -> bool: Allows deletion of an existing datacenter object The deletion of a datacenter is only possible if the datacenter has no hosts (servers) associated with any child items. :param uuid: The unique identifier of the datacenter to delete :type uuid: str :param delete_input: Optional parameters for the delete operation :type delete_input: DeleteDataCenterInput, optional :returns bool: If the query was successful :raises GraphQLError: An error with the GraphQL endpoint.
- def update_datacenter(self, uuid: str, update_input: UpdateDataCenterInput) -> DataCenter: Allows updating properties of an existing datacenter object :param uuid: The unique identifier of the datacenter to update :type uuid: str :param update_input: A property definition for the datacenter updates :type update_input: UpdateDataCenterInput :returns DataCenter: The updated datacenter object. :raises GraphQLError: An error with the GraphQL endpoint.

Implement the Python class `DatacentersMixin` described below.

Class description:
Mixin to add datacenter related methods to the GraphQL client

Method signatures and docstrings:
- def get_datacenters(self, page: PageInput=None, dc_filter: DataCenterFilter=None, sort: DataCenterSort=None) -> DataCenterList: Retrieves a list of datacenter objects :param page: The requested page from the server. This is an optional argument and if omitted the server will default to returning the first page with a maximum of ``100`` items. :type page: PageInput, optional :param dc_filter: A filter object to filter the datacenters on the server. If omitted, the server will return all objects as a paginated response. :type dc_filter: DataCenterFilter, optional :param sort: A sort definition object to sort the datacenter objects on supported properties. If omitted objects are returned in the order as they were created in. :type sort: DataCenterSort, optional :returns DataCenterList: A paginated list of datacenters. :
- def create_datacenter(self, create_input: CreateDataCenterInput=None) -> DataCenter: Allows creation of a new datacenter object A datacenter record allows customers to logically organize their infrastructure by physical location and associate address and contact information with the physical location. This is useful for effective support case handling and reporting purposes. :param create_input: A property definition for the new datacenter :type create_input: CreateDataCenterInput :returns DataCenter: The new datacenter. :raises GraphQLError: An error with the GraphQL endpoint.
- def delete_datacenter(self, uuid: str, delete_input: DeleteDataCenterInput=None) -> bool: Allows deletion of an existing datacenter object The deletion of a datacenter is only possible if the datacenter has no hosts (servers) associated with any child items. :param uuid: The unique identifier of the datacenter to delete :type uuid: str :param delete_input: Optional parameters for the delete operation :type delete_input: DeleteDataCenterInput, optional :returns bool: If the query was successful :raises GraphQLError: An error with the GraphQL endpoint.
- def update_datacenter(self, uuid: str, update_input: UpdateDataCenterInput) -> DataCenter: Allows updating properties of an existing datacenter object :param uuid: The unique identifier of the datacenter to update :type uuid: str :param update_input: A property definition for the datacenter updates :type update_input: UpdateDataCenterInput :returns DataCenter: The updated datacenter object. :raises GraphQLError: An error with the GraphQL endpoint.

<|skeleton|>
class DatacentersMixin:
    """Mixin to add datacenter related methods to the GraphQL client"""

    def get_datacenters(self, page: PageInput=None, dc_filter: DataCenterFilter=None, sort: DataCenterSort=None) -> DataCenterList:
        """Retrieves a list of datacenter objects :param page: The requested page from the server. This is an optional argument and if omitted the server will default to returning the first page with a maximum of ``100`` items. :type page: PageInput, optional :param dc_filter: A filter object to filter the datacenters on the server. If omitted, the server will return all objects as a paginated response. :type dc_filter: DataCenterFilter, optional :param sort: A sort definition object to sort the datacenter objects on supported properties. If omitted objects are returned in the order as they were created in. :type sort: DataCenterSort, optional :returns DataCenterList: A paginated list of datacenters. :"""
        <|body_0|>

    def create_datacenter(self, create_input: CreateDataCenterInput=None) -> DataCenter:
        """Allows creation of a new datacenter object A datacenter record allows customers to logically organize their infrastructure by physical location and associate address and contact information with the physical location. This is useful for effective support case handling and reporting purposes. :param create_input: A property definition for the new datacenter :type create_input: CreateDataCenterInput :returns DataCenter: The new datacenter. :raises GraphQLError: An error with the GraphQL endpoint."""
        <|body_1|>

    def delete_datacenter(self, uuid: str, delete_input: DeleteDataCenterInput=None) -> bool:
        """Allows deletion of an existing datacenter object The deletion of a datacenter is only possible if the datacenter has no hosts (servers) associated with any child items. :param uuid: The unique identifier of the datacenter to delete :type uuid: str :param delete_input: Optional parameters for the delete operation :type delete_input: DeleteDataCenterInput, optional :returns bool: If the query was successful :raises GraphQLError: An error with the GraphQL endpoint."""
        <|body_2|>

    def update_datacenter(self, uuid: str, update_input: UpdateDataCenterInput) -> DataCenter:
        """Allows updating properties of an existing datacenter object :param uuid: The unique identifier of the datacenter to update :type uuid: str :param update_input: A property definition for the datacenter updates :type update_input: UpdateDataCenterInput :returns DataCenter: The updated datacenter object. :raises GraphQLError: An error with the GraphQL endpoint."""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        parameters = dict()
        parameters['page'] = GraphQLParam(page, 'PageInput', False)
        parameters['filter'] = GraphQLParam(dc_filter, 'DataCenterFilter', False)
        parameters['sort'] = GraphQLParam(sort, 'DataCenterSort', False)
        response = self._query(name='getDataCenters', params=parameters, fields=DataCenterList.fields())
        return DataCenterList(response)
<|end_body_0|>

<|body_start_1|>
        parameters = dict()
        parameters['input'] = GraphQLParam(create_input, 'CreateDataCenterInput', True)
        response = self._mutation(name='createDataCenter', params=parameters, fields=DataCenter.fields())
        return DataCenter(response)
<|end_body_1|>

<|body_start_2|>
        parameters = dict()
        parameters['uuid'] = GraphQLParam(uuid, 'UUID', True)
        parameters['input'] = GraphQLParam(delete_input, 'DeleteDataCenterInput', False)
        response = self._mutation(name='deleteDataCenter', params=parameters, fields=None)
        return response
<|end_body_2|>

<|body_start_3|>
        parameters = dict()
        parameters['uuid'] = GraphQLParam(uuid, 'UUID', True)
        parameters['input'] = GraphQLParam(update_input, 'UpsertDataCenterInput', False)
        response = self._mutation(name='updateDataCenter', params=parameters, fields=DataCenter.fields())
        return DataCenter(response)
<|end_body_3|>

Solution:
class DatacentersMixin:
    """Mixin to add datacenter related methods to the GraphQL client"""

    def get_datacenters(self, page: PageInput=None, dc_filter: DataCenterFilter=None, sort: DataCenterSort=None) -> DataCenterList:
        """Retrieves a list of datacenter objects :param page: The requested page from the server. This is an optional argument and if omitted the server will default to returning the first page with a maximum of ``100`` items. :type page: PageInput, optional :param dc_filter: A filter object to filter the datacenters on the server. If omitted, the server will return all objects as a paginated response. :type dc_filter: DataCenterFilter, optional :param sort: A sort definition object to sort the datacenter objects on supported properties. If omitted objects are returned in the order as they were created in. :type sort: DataCenterSort, optional :returns DataCenterList: A paginated list of datacenters. :"""
        parameters = dict()
        parameters['page'] = GraphQLParam(page, 'PageInput', False)
        parameters['filter'] = GraphQLParam(dc_filter, 'DataCenterFilter', False)
        parameters['sort'] = GraphQLParam(sort, 'DataCenterSort', False)
        response = self._query(name='getDataCenters', params=parameters, fields=DataCenterList.fields())
        return DataCenterList(response)

    def create_datacenter(self, create_input: CreateDataCenterInput=None) -> DataCenter:
        """Allows creation of a new datacenter object A datacenter record allows customers to logically organize their infrastructure by physical location and associate address and contact information with the physical location. This is useful for effective support case handling and reporting purposes. :param create_input: A property definition for the new datacenter :type create_input: CreateDataCenterInput :returns DataCenter: The new datacenter. :raises GraphQLError: An error with the GraphQL endpoint."""
        parameters = dict()
        parameters['input'] = GraphQLParam(create_input, 'CreateDataCenterInput', True)
        response = self._mutation(name='createDataCenter', params=parameters, fields=DataCenter.fields())
        return DataCenter(response)

    def delete_datacenter(self, uuid: str, delete_input: DeleteDataCenterInput=None) -> bool:
        """Allows deletion of an existing datacenter object The deletion of a datacenter is only possible if the datacenter has no hosts (servers) associated with any child items. :param uuid: The unique identifier of the datacenter to delete :type uuid: str :param delete_input: Optional parameters for the delete operation :type delete_input: DeleteDataCenterInput, optional :returns bool: If the query was successful :raises GraphQLError: An error with the GraphQL endpoint."""
        parameters = dict()
        parameters['uuid'] = GraphQLParam(uuid, 'UUID', True)
        parameters['input'] = GraphQLParam(delete_input, 'DeleteDataCenterInput', False)
        response = self._mutation(name='deleteDataCenter', params=parameters, fields=None)
        return response

    def update_datacenter(self, uuid: str, update_input: UpdateDataCenterInput) -> DataCenter:
        """Allows updating properties of an existing datacenter object :param uuid: The unique identifier of the datacenter to update :type uuid: str :param update_input: A property definition for the datacenter updates :type update_input: UpdateDataCenterInput :returns DataCenter: The updated datacenter object. :raises GraphQLError: An error with the GraphQL endpoint."""
        parameters = dict()
        parameters['uuid'] = GraphQLParam(uuid, 'UUID', True)
        parameters['input'] = GraphQLParam(update_input, 'UpsertDataCenterInput', False)
        response = self._mutation(name='updateDataCenter', params=parameters, fields=DataCenter.fields())
        return DataCenter(response)


middleNode

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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def middleNode(self, head): 解題思路：暴力法。 從頭開始遍歷並計算linked list的長度，找完後再回頭遍歷middle node :type head: ListNode :rtype: ListNode
- def middleNode2(self, head): 解題思路： 例用兩個指標fast和slow從頭遍歷，當fast走完linked list時，slow會剛好停在middle node 時間複雜度: O(N) 空間複雜度: O(1) :param head: :return:

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def middleNode(self, head): 解題思路：暴力法。 從頭開始遍歷並計算linked list的長度，找完後再回頭遍歷middle node :type head: ListNode :rtype: ListNode
- def middleNode2(self, head): 解題思路： 例用兩個指標fast和slow從頭遍歷，當fast走完linked list時，slow會剛好停在middle node 時間複雜度: O(N) 空間複雜度: O(1) :param head: :return:

<|skeleton|>
class Solution:

    def middleNode(self, head):
        """解題思路：暴力法。 從頭開始遍歷並計算linked list的長度，找完後再回頭遍歷middle node :type head: ListNode :rtype: ListNode"""
        <|body_0|>

    def middleNode2(self, head):
        """解題思路： 例用兩個指標fast和slow從頭遍歷，當fast走完linked list時，slow會剛好停在middle node 時間複雜度: O(N) 空間複雜度: O(1) :param head: :return:"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        node = head
        count = 0
        while node:
            count += 1
            node = node.next
        node = head
        for _ in range(count // 2):
            node = node.next
        return node
<|end_body_0|>

<|body_start_1|>
        fast = slow = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        return slow
<|end_body_1|>

Solution:
class Solution:
    def middleNode(self, head):
        """解題思路：暴力法。 從頭開始遍歷並計算linked list的長度，找完後再回頭遍歷middle node :type head: ListNode :rtype: ListNode"""
        node = head
        count = 0
        while node:
            count += 1
            node = node.next
        node = head
        for _ in range(count // 2):
            node = node.next
        return node

    def middleNode2(self, head):
        """解題思路： 例用兩個指標fast和slow從頭遍歷，當fast走完linked list時，slow會剛好停在middle node 時間複雜度: O(N) 空間複雜度: O(1) :param head: :return:"""
        fast = slow = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        return slow


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

Class description:
base class has some common fields and functions.

Method signatures and docstrings:
- def __init__(self, d_model, d_k, d_v, sequence_length, h, batch_size, num_layer=6, decoder_sent_length=None): :param d_model: :param d_k: :param d_v: :param sequence_length: :param h: :param batch_size: :param embedded_words: shape:[batch_size,sequence_length,embed_size]
- def sub_layer_postion_wise_feed_forward(self, x, layer_index): position-wise feed forward. you can implement it as feed forward network, or two layers of CNN. :param x: shape should be:[batch_size,sequence_length,d_model] :param layer_index: index of layer number :return: [batch_size,sequence_length,d_model]
- def sub_layer_multi_head_attention(self, layer_index, Q, K_s, V_s, mask=None, is_training=None, dropout_keep_prob=0.9): multi head attention as sub layer :param layer_index: index of layer number :param Q: shape should be: [batch_size,sequence_length,embed_size] :param k_s: shape should be: [batch_size,sequence_length,embed_size] :param mask: when use mask,illegal connection will be mask as huge big negative value.so it's possiblitity will become zero. :return: output of multi head attention.shape:[batch_size,sequence_length,d_model]
- def sub_layer_layer_norm_residual_connection(self, layer_input, layer_output, layer_index, dropout_keep_prob=0.9, use_residual_conn=True, sub_layer_name='layer1'): layer norm & residual connection :param input: [batch_size,equence_length,d_model] :param output:[batch_size,sequence_length,d_model] :return:

Implement the Python class `BaseClass` described below.

Class description:
base class has some common fields and functions.

Method signatures and docstrings:
- def __init__(self, d_model, d_k, d_v, sequence_length, h, batch_size, num_layer=6, decoder_sent_length=None): :param d_model: :param d_k: :param d_v: :param sequence_length: :param h: :param batch_size: :param embedded_words: shape:[batch_size,sequence_length,embed_size]
- def sub_layer_postion_wise_feed_forward(self, x, layer_index): position-wise feed forward. you can implement it as feed forward network, or two layers of CNN. :param x: shape should be:[batch_size,sequence_length,d_model] :param layer_index: index of layer number :return: [batch_size,sequence_length,d_model]
- def sub_layer_multi_head_attention(self, layer_index, Q, K_s, V_s, mask=None, is_training=None, dropout_keep_prob=0.9): multi head attention as sub layer :param layer_index: index of layer number :param Q: shape should be: [batch_size,sequence_length,embed_size] :param k_s: shape should be: [batch_size,sequence_length,embed_size] :param mask: when use mask,illegal connection will be mask as huge big negative value.so it's possiblitity will become zero. :return: output of multi head attention.shape:[batch_size,sequence_length,d_model]
- def sub_layer_layer_norm_residual_connection(self, layer_input, layer_output, layer_index, dropout_keep_prob=0.9, use_residual_conn=True, sub_layer_name='layer1'): layer norm & residual connection :param input: [batch_size,equence_length,d_model] :param output:[batch_size,sequence_length,d_model] :return:

<|skeleton|>
class BaseClass:
    """base class has some common fields and functions."""

    def __init__(self, d_model, d_k, d_v, sequence_length, h, batch_size, num_layer=6, decoder_sent_length=None):
        """:param d_model: :param d_k: :param d_v: :param sequence_length: :param h: :param batch_size: :param embedded_words: shape:[batch_size,sequence_length,embed_size]"""
        <|body_0|>

    def sub_layer_postion_wise_feed_forward(self, x, layer_index):
        """position-wise feed forward. you can implement it as feed forward network, or two layers of CNN. :param x: shape should be:[batch_size,sequence_length,d_model] :param layer_index: index of layer number :return: [batch_size,sequence_length,d_model]"""
        <|body_1|>

    def sub_layer_multi_head_attention(self, layer_index, Q, K_s, V_s, mask=None, is_training=None, dropout_keep_prob=0.9):
        """multi head attention as sub layer :param layer_index: index of layer number :param Q: shape should be: [batch_size,sequence_length,embed_size] :param k_s: shape should be: [batch_size,sequence_length,embed_size] :param mask: when use mask,illegal connection will be mask as huge big negative value.so it's possiblitity will become zero. :return: output of multi head attention.shape:[batch_size,sequence_length,d_model]"""
        <|body_2|>

    def sub_layer_layer_norm_residual_connection(self, layer_input, layer_output, layer_index, dropout_keep_prob=0.9, use_residual_conn=True, sub_layer_name='layer1'):
        """layer norm & residual connection :param input: [batch_size,equence_length,d_model] :param output:[batch_size,sequence_length,d_model] :return:"""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        self.d_model = d_model
        self.d_k = d_k
        self.d_v = d_v
        self.sequence_length = sequence_length
        self.h = h
        self.num_layer = num_layer
        self.batch_size = batch_size
        self.decoder_sent_length = decoder_sent_length
<|end_body_0|>

<|body_start_1|>
        with tf.variable_scope('sub_layer_postion_wise_feed_forward' + str(layer_index)):
            postion_wise_feed_forward = PositionWiseFeedFoward(x, layer_index, d_model=self.d_model, d_ff=self.d_model * 4)
            postion_wise_feed_forward_output = postion_wise_feed_forward.position_wise_feed_forward_fn()
        return postion_wise_feed_forward_output
<|end_body_1|>

<|body_start_2|>
        with tf.variable_scope('base_mode_sub_layer_multi_head_attention_' + str(layer_index)):
            multi_head_attention_class = MultiHeadAttention(Q, K_s, V_s, self.d_model, self.d_k, self.d_v, self.sequence_length, self.h, is_training=is_training, mask=mask, dropout_rate=1.0 - dropout_keep_prob)
            sub_layer_multi_head_attention_output = multi_head_attention_class.multi_head_attention_fn()
        return sub_layer_multi_head_attention_output
<|end_body_2|>

<|body_start_3|>
        variable_scope = 'sub_layer_layer_norm_residual_connection_' + str(layer_index) + '_' + sub_layer_name
        with tf.variable_scope(variable_scope):
            layer_norm_residual_conn = LayerNormResidualConnection(layer_input, layer_output, layer_index, residual_dropout=1 - dropout_keep_prob, use_residual_conn=use_residual_conn)
            output = layer_norm_residual_conn.layer_norm_residual_connection()
        return output
<|end_body_3|>

Solution:
class BaseClass:
    """base class has some common fields and functions."""

    def __init__(self, d_model, d_k, d_v, sequence_length, h, batch_size, num_layer=6, decoder_sent_length=None):
        """:param d_model: :param d_k: :param d_v: :param sequence_length: :param h: :param batch_size: :param embedded_words: shape:[batch_size,sequence_length,embed_size]"""
        self.d_model = d_model
        self.d_k = d_k
        self.d_v = d_v
        self.sequence_length = sequence_length
        self.h = h
        self.num_layer = num_layer
        self.batch_size = batch_size
        self.decoder_sent_length = decoder_sent_length

    def sub_layer_postion_wise_feed_forward(self, x, layer_index):
        """position-wise feed forward. you can implement it as feed forward network, or two layers of CNN. :param x: shape should be:[batch_size,sequence_length,d_model] :param layer_index: index of layer number :return: [batch_size,sequence_length,d_model]"""
        with tf.variable_scope('sub_layer_postion_wise_feed_forward' + str(layer_index)):
            postion_wise_feed_forward = PositionWiseFeedFoward(x, layer_index, d_model=self.d_model, d_ff=self.d_model * 4)
            postion_wise_feed_forward_output = postion_wise_feed_forward.position_wise_feed_forward_fn()
        return postion_wise_feed_forward_output

    def sub_layer_multi_head_attention(self, layer_index, Q, K_s, V_s, mask=None, is_training=None, dropout_keep_prob=0.9):
        """multi head attention as sub layer :param layer_index: index of layer number :param Q: shape should be: [batch_size,sequence_length,embed_size] :param k_s: shape should be: [batch_size,sequence_length,embed_size] :param mask: when use mask,illegal connection will be mask as huge big negative value.so it's possiblitity will become zero. :return: output of multi head attention.shape:[batch_size,sequence_length,d_model]"""
        with tf.variable_scope('base_mode_sub_layer_multi_head_attention_' + str(layer_index)):
            multi_head_attention_class = MultiHeadAttention(Q, K_s, V_s, self.d_model, self.d_k, self.d_v, self.sequence_length, self.h, is_training=is_training, mask=mask, dropout_rate=1.0 - dropout_keep_prob)
            sub_layer_multi_head_attention_output = multi_head_attention_class.multi_head_attention_fn()
        return sub_layer_multi_head_attention_output

    def sub_layer_layer_norm_residual_connection(self, layer_input, layer_output, layer_index, dropout_keep_prob=0.9, use_residual_conn=True, sub_layer_name='layer1'):
        """layer norm & residual connection :param input: [batch_size,equence_length,d_model] :param output:[batch_size,sequence_length,d_model] :return:"""
        variable_scope = 'sub_layer_layer_norm_residual_connection_' + str(layer_index) + '_' + sub_layer_name
        with tf.variable_scope(variable_scope):
            layer_norm_residual_conn = LayerNormResidualConnection(layer_input, layer_output, layer_index, residual_dropout=1 - dropout_keep_prob, use_residual_conn=use_residual_conn)
            output = layer_norm_residual_conn.layer_norm_residual_connection()
        return output


patch

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

Class description:
Implement the TicketResource class.

Method signatures and docstrings:
- def post(self, ticket_num): Метод для внесения лотирейного билета в базу
- def get(self, ticket_num): Метод для получения информации о лотирейном билете
- def patch(self, ticket_num): Метод для изменения статуса билета (вызвается во время покупки билета в ларьке)

Implement the Python class `TicketResource` described below.

Class description:
Implement the TicketResource class.

Method signatures and docstrings:
- def post(self, ticket_num): Метод для внесения лотирейного билета в базу
- def get(self, ticket_num): Метод для получения информации о лотирейном билете
- def patch(self, ticket_num): Метод для изменения статуса билета (вызвается во время покупки билета в ларьке)

<|skeleton|>
class TicketResource:

    def post(self, ticket_num):
        """Метод для внесения лотирейного билета в базу"""
        <|body_0|>

    def get(self, ticket_num):
        """Метод для получения информации о лотирейном билете"""
        <|body_1|>

    def patch(self, ticket_num):
        """Метод для изменения статуса билета (вызвается во время покупки билета в ларьке)"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        global DataBase
        json_data = lottery_ns.payload
        if ticket_num not in DataBase:
            ticket_fields = json_data['fields']
            ticket_price = json_data['price']
            if len(ticket_fields) != 3:
                return ('Количество полей в билете должно быть равно 3', 400)
            new_ticket = Ticket(ticket_num, ticket_fields, ticket_price)
            DataBase[ticket_num] = new_ticket
            return new_ticket.jsonify()
        else:
            return ('Билет с этим номером уже есть в базе', 400)
<|end_body_0|>

<|body_start_1|>
        global DataBase
        if ticket_num in DataBase:
            return DataBase[ticket_num].jsonify()
        else:
            return ('Лотерейный билет не найден', 404)
<|end_body_1|>

<|body_start_2|>
        global DataBase
        if ticket_num in DataBase:
            DataBase[ticket_num].sell()
            return DataBase[ticket_num].jsonify()
        else:
            lottery_ns.abort(404)
<|end_body_2|>

Solution:
class TicketResource:
    def post(self, ticket_num):
        """Метод для внесения лотирейного билета в базу"""
        global DataBase
        json_data = lottery_ns.payload
        if ticket_num not in DataBase:
            ticket_fields = json_data['fields']
            ticket_price = json_data['price']
            if len(ticket_fields) != 3:
                return ('Количество полей в билете должно быть равно 3', 400)
            new_ticket = Ticket(ticket_num, ticket_fields, ticket_price)
            DataBase[ticket_num] = new_ticket
            return new_ticket.jsonify()
        else:
            return ('Билет с этим номером уже есть в базе', 400)

    def get(self, ticket_num):
        """Метод для получения информации о лотирейном билете"""
        global DataBase
        if ticket_num in DataBase:
            return DataBase[ticket_num].jsonify()
        else:
            return ('Лотерейный билет не найден', 404)

    def patch(self, ticket_num):
        """Метод для изменения статуса билета (вызвается во время покупки билета в ларьке)"""
        global DataBase
        if ticket_num in DataBase:
            DataBase[ticket_num].sell()
            return DataBase[ticket_num].jsonify()
        else:
            lottery_ns.abort(404)


forward

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

Class description:
Implement the _RFCN_header class.

Method signatures and docstrings:
- def __init__(self, input_dim, n_classes, class_ag, k=3): :param input_dim: feature map channel number :param n_classes: :param class_ag: :param k: grid size
- def forward(self, x): :param feat: [batch_size, channel, H, W] :param rois: [batch_size, num, 5] :return:

Implement the Python class `_RFCN_header` described below.

Class description:
Implement the _RFCN_header class.

Method signatures and docstrings:
- def __init__(self, input_dim, n_classes, class_ag, k=3): :param input_dim: feature map channel number :param n_classes: :param class_ag: :param k: grid size
- def forward(self, x): :param feat: [batch_size, channel, H, W] :param rois: [batch_size, num, 5] :return:

<|skeleton|>
class _RFCN_header:

    def __init__(self, input_dim, n_classes, class_ag, k=3):
        """:param input_dim: feature map channel number :param n_classes: :param class_ag: :param k: grid size"""
        <|body_0|>

    def forward(self, x):
        """:param feat: [batch_size, channel, H, W] :param rois: [batch_size, num, 5] :return:"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        super(_RFCN_header, self).__init__(input_dim, n_classes, class_ag)
        self.position_sensitive_score_map = nn.Conv2d(input_dim, k ** 2 * n_classes, kernel_size=1)
        if class_ag:
            self.position_sensitive_bbox_map = nn.Conv2d(input_dim, k ** 2 * 4, kernel_size=1)
        else:
            self.position_sensitive_bbox_map = nn.Conv2d(input_dim, k ** 2 * 4 * n_classes, kernel_size=1)
        self.k = k
<|end_body_0|>

<|body_start_1|>
        feat = x[0]
        rois = x[1]
        score_map = self.position_sensitive_score_map(feat)
        bbox_map = self.position_sensitive_bbox_map(feat)
<|end_body_1|>

Solution:
class _RFCN_header:
    def __init__(self, input_dim, n_classes, class_ag, k=3):
        """:param input_dim: feature map channel number :param n_classes: :param class_ag: :param k: grid size"""
        super(_RFCN_header, self).__init__(input_dim, n_classes, class_ag)
        self.position_sensitive_score_map = nn.Conv2d(input_dim, k ** 2 * n_classes, kernel_size=1)
        if class_ag:
            self.position_sensitive_bbox_map = nn.Conv2d(input_dim, k ** 2 * 4, kernel_size=1)
        else:
            self.position_sensitive_bbox_map = nn.Conv2d(input_dim, k ** 2 * 4 * n_classes, kernel_size=1)
        self.k = k

    def forward(self, x):
        """:param feat: [batch_size, channel, H, W] :param rois: [batch_size, num, 5] :return:"""
        feat = x[0]
        rois = x[1]
        score_map = self.position_sensitive_score_map(feat)
        bbox_map = self.position_sensitive_bbox_map(feat)


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

Class description:
Implement the DenseVectorRocchioPrf class.

Method signatures and docstrings:
- def __init__(self, alpha: float, beta: float, gamma: float, topk: int, bottomk: int): Parameters ---------- alpha : float Rocchio parameter, controls the weight assigned to the original query embedding. beta : float Rocchio parameter, controls the weight assigned to the positive document embeddings. gamma : float Rocchio parameter, controls the weight assigned to the negative document embeddings. topk : int Rocchio parameter, set topk documents as positive document feedbacks. bottomk : int Rocchio parameter, set bottomk documents as negative document feedbacks.
- def get_prf_q_emb(self, emb_qs: np.ndarray=None, prf_candidates: List[PRFDenseSearchResult]=None): Perform Rocchio PRF with Dense Vectors Parameters ---------- emb_qs : np.ndarray query embedding prf_candidates : List[PRFDenseSearchResult] List of PRFDenseSearchResult, contains document embeddings. Returns ------- np.ndarray return new query embeddings
- def get_batch_prf_q_emb(self, topic_ids: List[str]=None, emb_qs: np.ndarray=None, prf_candidates: Dict[str, List[PRFDenseSearchResult]]=None): Perform Rocchio PRF with Dense Vectors Parameters ---------- topic_ids : List[str] List of topic ids. emb_qs : np.ndarray Query embeddings prf_candidates : List[PRFDenseSearchResult] List of PRFDenseSearchResult, contains document embeddings. Returns ------- np.ndarray return new query embeddings

Implement the Python class `DenseVectorRocchioPrf` described below.

Class description:
Implement the DenseVectorRocchioPrf class.

Method signatures and docstrings:
- def __init__(self, alpha: float, beta: float, gamma: float, topk: int, bottomk: int): Parameters ---------- alpha : float Rocchio parameter, controls the weight assigned to the original query embedding. beta : float Rocchio parameter, controls the weight assigned to the positive document embeddings. gamma : float Rocchio parameter, controls the weight assigned to the negative document embeddings. topk : int Rocchio parameter, set topk documents as positive document feedbacks. bottomk : int Rocchio parameter, set bottomk documents as negative document feedbacks.
- def get_prf_q_emb(self, emb_qs: np.ndarray=None, prf_candidates: List[PRFDenseSearchResult]=None): Perform Rocchio PRF with Dense Vectors Parameters ---------- emb_qs : np.ndarray query embedding prf_candidates : List[PRFDenseSearchResult] List of PRFDenseSearchResult, contains document embeddings. Returns ------- np.ndarray return new query embeddings
- def get_batch_prf_q_emb(self, topic_ids: List[str]=None, emb_qs: np.ndarray=None, prf_candidates: Dict[str, List[PRFDenseSearchResult]]=None): Perform Rocchio PRF with Dense Vectors Parameters ---------- topic_ids : List[str] List of topic ids. emb_qs : np.ndarray Query embeddings prf_candidates : List[PRFDenseSearchResult] List of PRFDenseSearchResult, contains document embeddings. Returns ------- np.ndarray return new query embeddings

<|skeleton|>
class DenseVectorRocchioPrf:

    def __init__(self, alpha: float, beta: float, gamma: float, topk: int, bottomk: int):
        """Parameters ---------- alpha : float Rocchio parameter, controls the weight assigned to the original query embedding. beta : float Rocchio parameter, controls the weight assigned to the positive document embeddings. gamma : float Rocchio parameter, controls the weight assigned to the negative document embeddings. topk : int Rocchio parameter, set topk documents as positive document feedbacks. bottomk : int Rocchio parameter, set bottomk documents as negative document feedbacks."""
        <|body_0|>

    def get_prf_q_emb(self, emb_qs: np.ndarray=None, prf_candidates: List[PRFDenseSearchResult]=None):
        """Perform Rocchio PRF with Dense Vectors Parameters ---------- emb_qs : np.ndarray query embedding prf_candidates : List[PRFDenseSearchResult] List of PRFDenseSearchResult, contains document embeddings. Returns ------- np.ndarray return new query embeddings"""
        <|body_1|>

    def get_batch_prf_q_emb(self, topic_ids: List[str]=None, emb_qs: np.ndarray=None, prf_candidates: Dict[str, List[PRFDenseSearchResult]]=None):
        """Perform Rocchio PRF with Dense Vectors Parameters ---------- topic_ids : List[str] List of topic ids. emb_qs : np.ndarray Query embeddings prf_candidates : List[PRFDenseSearchResult] List of PRFDenseSearchResult, contains document embeddings. Returns ------- np.ndarray return new query embeddings"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        DenseVectorPrf.__init__(self)
        self.alpha = alpha
        self.beta = beta
        self.gamma = gamma
        self.topk = topk
        self.bottomk = bottomk
<|end_body_0|>

<|body_start_1|>
        all_candidate_embs = [item.vectors for item in prf_candidates]
        weighted_query_embs = self.alpha * emb_qs
        weighted_mean_pos_doc_embs = self.beta * np.mean(all_candidate_embs[:self.topk], axis=0)
        new_emb_q = weighted_query_embs + weighted_mean_pos_doc_embs
        if self.bottomk > 0:
            weighted_mean_neg_doc_embs = self.gamma * np.mean(all_candidate_embs[-self.bottomk:], axis=0)
            new_emb_q -= weighted_mean_neg_doc_embs
        return new_emb_q
<|end_body_1|>

<|body_start_2|>
        qids = list()
        new_emb_qs = list()
        for index, topic_id in enumerate(topic_ids):
            qids.append(topic_id)
            new_emb_qs.append(self.get_prf_q_emb(emb_qs[index], prf_candidates[topic_id]))
        new_emb_qs = np.array(new_emb_qs).astype('float32')
        return new_emb_qs
<|end_body_2|>

Solution:
class DenseVectorRocchioPrf:
    def __init__(self, alpha: float, beta: float, gamma: float, topk: int, bottomk: int):
        """Parameters ---------- alpha : float Rocchio parameter, controls the weight assigned to the original query embedding. beta : float Rocchio parameter, controls the weight assigned to the positive document embeddings. gamma : float Rocchio parameter, controls the weight assigned to the negative document embeddings. topk : int Rocchio parameter, set topk documents as positive document feedbacks. bottomk : int Rocchio parameter, set bottomk documents as negative document feedbacks."""
        DenseVectorPrf.__init__(self)
        self.alpha = alpha
        self.beta = beta
        self.gamma = gamma
        self.topk = topk
        self.bottomk = bottomk

    def get_prf_q_emb(self, emb_qs: np.ndarray=None, prf_candidates: List[PRFDenseSearchResult]=None):
        """Perform Rocchio PRF with Dense Vectors Parameters ---------- emb_qs : np.ndarray query embedding prf_candidates : List[PRFDenseSearchResult] List of PRFDenseSearchResult, contains document embeddings. Returns ------- np.ndarray return new query embeddings"""
        all_candidate_embs = [item.vectors for item in prf_candidates]
        weighted_query_embs = self.alpha * emb_qs
        weighted_mean_pos_doc_embs = self.beta * np.mean(all_candidate_embs[:self.topk], axis=0)
        new_emb_q = weighted_query_embs + weighted_mean_pos_doc_embs
        if self.bottomk > 0:
            weighted_mean_neg_doc_embs = self.gamma * np.mean(all_candidate_embs[-self.bottomk:], axis=0)
            new_emb_q -= weighted_mean_neg_doc_embs
        return new_emb_q

    def get_batch_prf_q_emb(self, topic_ids: List[str]=None, emb_qs: np.ndarray=None, prf_candidates: Dict[str, List[PRFDenseSearchResult]]=None):
        """Perform Rocchio PRF with Dense Vectors Parameters ---------- topic_ids : List[str] List of topic ids. emb_qs : np.ndarray Query embeddings prf_candidates : List[PRFDenseSearchResult] List of PRFDenseSearchResult, contains document embeddings. Returns ------- np.ndarray return new query embeddings"""
        qids = list()
        new_emb_qs = list()
        for index, topic_id in enumerate(topic_ids):
            qids.append(topic_id)
            new_emb_qs.append(self.get_prf_q_emb(emb_qs[index], prf_candidates[topic_id]))
        new_emb_qs = np.array(new_emb_qs).astype('float32')
        return new_emb_qs


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

Class description:
Implement the TestBisectSession class.

Method signatures and docstrings:
- def test_two_cached_only_fast(self): Simple case with two cached commits and only the fast command.
- def test_only_fast(self): Mix of cached and uncached with only the fast command.
- def test_fast_and_slow(self): Mix of cached and uncached with fast and slow command.

Implement the Python class `TestBisectSession` described below.

Class description:
Implement the TestBisectSession class.

Method signatures and docstrings:
- def test_two_cached_only_fast(self): Simple case with two cached commits and only the fast command.
- def test_only_fast(self): Mix of cached and uncached with only the fast command.
- def test_fast_and_slow(self): Mix of cached and uncached with fast and slow command.

<|skeleton|>
class TestBisectSession:

    def test_two_cached_only_fast(self):
        """Simple case with two cached commits and only the fast command."""
        <|body_0|>

    def test_only_fast(self):
        """Mix of cached and uncached with only the fast command."""
        <|body_1|>

    def test_fast_and_slow(self):
        """Mix of cached and uncached with fast and slow command."""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        BISECT_LOG = 'git bisect start\n# status: waiting for both good and bad commits\n# good: [c1] Fake good commit\ngit bisect good c1\n# status: waiting for bad commit, 1 good commit known\n# bad: [c2] Fake bad commit\ngit bisect bad c2\n# first bad commit: [c2] Fake bad commit\n'
        git = MockableGitController()
        git._git = MagicMock(return_value=(0, '', ''))
        git.bisect_view = MagicMock(return_value=[(CommitHash('c1'), 'Commit description'), (CommitHash('c2'), 'Commit description')])
        git.bisect_log = MagicMock(return_value=BisectLog(BISECT_LOG))
        session = BisectSession(git, cache_keys=set(['c1', 'c2']))
        result: BisectLog = session.run('c1', 'c2', ['fast_script.sh'])
        self.assertEqual(result.candidates, ['c2'])
        git._git.assert_has_calls([call('bisect', 'start'), call('bisect', 'good', 'c1'), call('bisect', 'bad', 'c2'), call('bisect', 'run', 'fast_script.sh'), call('bisect', 'reset')])
        git.bisect_log.assert_called_once_with()
        git.bisect_view.assert_called_once_with()
<|end_body_0|>

<|body_start_1|>
        BISECT_LOG = 'git bisect start\n# status: waiting for both good and bad commits\n# skip: [c2] Skipped commit\ngit bisect skip c2\n# good: [c1] Fake good commit\ngit bisect good c1\n# status: waiting for bad commit, 1 good commit known\n# bad: [c3] Fake bad commit\ngit bisect bad c3\n# only skipped commits left to test\n# possible first bad commit: [c2] Skipped commit\n# possible first bad commit: [c3] Fake bad commit\n'
        git = MockableGitController()
        git._git = MagicMock(return_value=(0, '', ''))
        git.bisect_view = MagicMock(return_value=[(CommitHash('c1'), 'Fake good commit'), (CommitHash('c2'), 'Skipped commit'), (CommitHash('c3'), 'Fake bad commit')])
        git.bisect_log = MagicMock(return_value=BisectLog(BISECT_LOG))
        session = BisectSession(git, cache_keys=set(['c1', 'c3']))
        bisect_log = session.run('c1', 'c3', ['fast_script.sh'])
        self.assertEqual(bisect_log.candidates, ['c2', 'c3'])
        git._git.assert_has_calls([call('bisect', 'start'), call('bisect', 'good', 'c1'), call('bisect', 'bad', 'c3'), call('bisect', 'skip', 'c2'), call('bisect', 'run', 'fast_script.sh')])
        git.bisect_log.assert_called_once_with()
        git.bisect_view.assert_called_once_with()
<|end_body_1|>

<|body_start_2|>
        BISECT_LOG_1 = 'git bisect start\n# status: waiting for both good and bad commits\n# good: [c1] Commit 1\ngit bisect good c1\n# status: waiting for bad commit, 1 good commit known\n# bad: [c5] Commit 5\ngit bisect bad c5\n# skip: [c3] Commit 3\ngit bisect skip c3\n# skip: [c4] Commit 4\ngit bisect skip c4\n# good: [c2] Commit 2\ngit bisect good c2\n# only skipped commits left to test\n# possible first bad commit: [c3] Commit 3\n# possible first bad commit: [c4] Commit 4\n'
        BISECT_LOG_2 = 'git bisect start\n# status: waiting for both good and bad commits\n# good: [c1] Commit 1\ngit bisect good c1\n# status: waiting for bad commit, 1 good commit known\n# bad: [c5] Commit 5\ngit bisect bad c5\n# good: [c2] Commit 2\ngit bisect good c2\n# good: [c3] Commit 3\ngit bisect good c3\n# bad: [c4] Commit 4\ngit bisect bad c4\n# first bad commit: [c4] Commit 4\n'
        parsed_bisect_logs = [BisectLog(BISECT_LOG_1), BisectLog(BISECT_LOG_2)]
        git = MockableGitController()
        git._git = MagicMock(return_value=(0, '', ''))
        git.bisect_log = MagicMock(side_effect=parsed_bisect_logs)
        git.bisect_view = MagicMock(return_value=[(CommitHash('c1'), 'Commit 1'), (CommitHash('c2'), 'Commit 2'), (CommitHash('c3'), 'Commit 3'), (CommitHash('c4'), 'Commit 4'), (CommitHash('c5'), 'Commit 5')])
        session = BisectSession(git, cache_keys=set(['c1', 'c2']))
        bisect_log = session.run('c1', 'c5', ['fast_script.sh'], ['slow_script.sh'])
        self.assertEqual(bisect_log.candidates, ['c4'])
        git._git.assert_has_calls([call('bisect', 'start'), call('bisect', 'good', 'c1'), call('bisect', 'bad', 'c5'), call('bisect', 'skip', 'c3', 'c4', 'c5'), call('bisect', 'run', 'fast_script.sh'), call('bisect', 'reset'), call('bisect', 'start'), call('bisect', 'good', 'c1'), call('bisect', 'bad', 'c5'), call('bisect', 'good', 'c2'), call('bisect', 'run', 'slow_script.sh')])
        git.bisect_log.assert_has_calls([call(), call()])
        git.bisect_view.assert_called_once_with()
<|end_body_2|>

Solution:
class TestBisectSession:
    def test_two_cached_only_fast(self):
        """Simple case with two cached commits and only the fast command."""
        BISECT_LOG = 'git bisect start\n# status: waiting for both good and bad commits\n# good: [c1] Fake good commit\ngit bisect good c1\n# status: waiting for bad commit, 1 good commit known\n# bad: [c2] Fake bad commit\ngit bisect bad c2\n# first bad commit: [c2] Fake bad commit\n'
        git = MockableGitController()
        git._git = MagicMock(return_value=(0, '', ''))
        git.bisect_view = MagicMock(return_value=[(CommitHash('c1'), 'Commit description'), (CommitHash('c2'), 'Commit description')])
        git.bisect_log = MagicMock(return_value=BisectLog(BISECT_LOG))
        session = BisectSession(git, cache_keys=set(['c1', 'c2']))
        result: BisectLog = session.run('c1', 'c2', ['fast_script.sh'])
        self.assertEqual(result.candidates, ['c2'])
        git._git.assert_has_calls([call('bisect', 'start'), call('bisect', 'good', 'c1'), call('bisect', 'bad', 'c2'), call('bisect', 'run', 'fast_script.sh'), call('bisect', 'reset')])
        git.bisect_log.assert_called_once_with()
        git.bisect_view.assert_called_once_with()

    def test_only_fast(self):
        """Mix of cached and uncached with only the fast command."""
        BISECT_LOG = 'git bisect start\n# status: waiting for both good and bad commits\n# skip: [c2] Skipped commit\ngit bisect skip c2\n# good: [c1] Fake good commit\ngit bisect good c1\n# status: waiting for bad commit, 1 good commit known\n# bad: [c3] Fake bad commit\ngit bisect bad c3\n# only skipped commits left to test\n# possible first bad commit: [c2] Skipped commit\n# possible first bad commit: [c3] Fake bad commit\n'
        git = MockableGitController()
        git._git = MagicMock(return_value=(0, '', ''))
        git.bisect_view = MagicMock(return_value=[(CommitHash('c1'), 'Fake good commit'), (CommitHash('c2'), 'Skipped commit'), (CommitHash('c3'), 'Fake bad commit')])
        git.bisect_log = MagicMock(return_value=BisectLog(BISECT_LOG))
        session = BisectSession(git, cache_keys=set(['c1', 'c3']))
        bisect_log = session.run('c1', 'c3', ['fast_script.sh'])
        self.assertEqual(bisect_log.candidates, ['c2', 'c3'])
        git._git.assert_has_calls([call('bisect', 'start'), call('bisect', 'good', 'c1'), call('bisect', 'bad', 'c3'), call('bisect', 'skip', 'c2'), call('bisect', 'run', 'fast_script.sh')])
        git.bisect_log.assert_called_once_with()
        git.bisect_view.assert_called_once_with()

    def test_fast_and_slow(self):
        """Mix of cached and uncached with fast and slow command."""
        BISECT_LOG_1 = 'git bisect start\n# status: waiting for both good and bad commits\n# good: [c1] Commit 1\ngit bisect good c1\n# status: waiting for bad commit, 1 good commit known\n# bad: [c5] Commit 5\ngit bisect bad c5\n# skip: [c3] Commit 3\ngit bisect skip c3\n# skip: [c4] Commit 4\ngit bisect skip c4\n# good: [c2] Commit 2\ngit bisect good c2\n# only skipped commits left to test\n# possible first bad commit: [c3] Commit 3\n# possible first bad commit: [c4] Commit 4\n'
        BISECT_LOG_2 = 'git bisect start\n# status: waiting for both good and bad commits\n# good: [c1] Commit 1\ngit bisect good c1\n# status: waiting for bad commit, 1 good commit known\n# bad: [c5] Commit 5\ngit bisect bad c5\n# good: [c2] Commit 2\ngit bisect good c2\n# good: [c3] Commit 3\ngit bisect good c3\n# bad: [c4] Commit 4\ngit bisect bad c4\n# first bad commit: [c4] Commit 4\n'
        parsed_bisect_logs = [BisectLog(BISECT_LOG_1), BisectLog(BISECT_LOG_2)]
        git = MockableGitController()
        git._git = MagicMock(return_value=(0, '', ''))
        git.bisect_log = MagicMock(side_effect=parsed_bisect_logs)
        git.bisect_view = MagicMock(return_value=[(CommitHash('c1'), 'Commit 1'), (CommitHash('c2'), 'Commit 2'), (CommitHash('c3'), 'Commit 3'), (CommitHash('c4'), 'Commit 4'), (CommitHash('c5'), 'Commit 5')])
        session = BisectSession(git, cache_keys=set(['c1', 'c2']))
        bisect_log = session.run('c1', 'c5', ['fast_script.sh'], ['slow_script.sh'])
        self.assertEqual(bisect_log.candidates, ['c4'])
        git._git.assert_has_calls([call('bisect', 'start'), call('bisect', 'good', 'c1'), call('bisect', 'bad', 'c5'), call('bisect', 'skip', 'c3', 'c4', 'c5'), call('bisect', 'run', 'fast_script.sh'), call('bisect', 'reset'), call('bisect', 'start'), call('bisect', 'good', 'c1'), call('bisect', 'bad', 'c5'), call('bisect', 'good', 'c2'), call('bisect', 'run', 'slow_script.sh')])
        git.bisect_log.assert_has_calls([call(), call()])
        git.bisect_view.assert_called_once_with()