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

Class description:
Implement the NetworksClient class.

Method signatures and docstrings:
- def __init__(self, url, auth_token, serialize_format=None, deserialize_format=None, tenant_id=None): @param url: Base URL for the networks service @type url: string @param auth_token: Auth token to be used for all requests @type auth_token: string @param serialize_format: Format for serializing requests @type serialize_format: string @param deserialize_format: Format for de-serializing responses @type deserialize_format: string @param tenant_id: optional tenant id to be included in the header if given @type tenant_id: string
- def create_network(self, name=None, admin_state_up=None, shared=None, tenant_id=None, requestslib_kwargs=None): @summary: Creates a Network @param name: human readable name for the network, may not be unique. (CRUD: CRU) @type name: string @param admin_state_up: true or false, the admin state of the network. If down, the network does not forward packets. Default value is True (CRUD: CRU) @type admin_state_up: bool @param shared: specifies if the network can be accessed by any tenant. Default value is False. (CRUD: CRU) @type shared: bool @param tenant_id: owner of the network. (CRUD: CR) @type tenant_id: string @return: network create response @rtype: Requests.response
- def update_network(self, network_id, name=None, admin_state_up=None, shared=None, tenant_id=None, requestslib_kwargs=None): @summary: Updates a specified Network @param network_id: The UUID for the network @type network_id: string @param name: human readable name for the network, may not be unique. (CRUD: CRU) @type name: string @param admin_state_up: true or false, the admin state of the network. If down, the network does not forward packets. Default value is True (CRUD: CRU) @type admin_state_up: bool @param shared: specifies if the network can be accessed by any tenant. Default value is False. (CRUD: CRU) @type shared: bool @param tenant_id: owner of the network. (CRUD: CR) @type tenant_id: string @return: update network response @rtype: Requests.response
- def get_network(self, network_id, requestslib_kwargs=None): @summary: Shows information for a specified network @param network_id: The UUID for the network @type network_id: string @return: get network response @rtype: Requests.response
- def list_networks(self, network_id=None, name=None, status=None, admin_state_up=None, shared=None, tenant_id=None, limit=None, marker=None, page_reverse=None, requestslib_kwargs=None): @summary: Lists networks, filtered by params if given @param network_id: network ID to filter by @type network_id: string @param name: network name to filter by @type name: string @param status: network status to filter by @type status: string @param admin_state_up: Admin state of the network to filter by @type admin_state_up: bool @param shared: If network is shared across tenants status to filter by @type shared: bool @param tenant_id: tenant ID network owner to filter by @type tenant_id: string @param limit: page size @type limit: int @param marker: Id of the last item of the previous page @type marker: string @param page_reverse: direction of the page @type page_reverse: bool @return: li
- def delete_network(self, network_id, requestslib_kwargs=None): @summary: Deletes a specified network and its associated resources @param network_id: The UUID for the network @type network_id: string @return: delete network response @rtype: Requests.response

Implement the Python class `NetworksClient` described below.

Class description:
Implement the NetworksClient class.

Method signatures and docstrings:
- def __init__(self, url, auth_token, serialize_format=None, deserialize_format=None, tenant_id=None): @param url: Base URL for the networks service @type url: string @param auth_token: Auth token to be used for all requests @type auth_token: string @param serialize_format: Format for serializing requests @type serialize_format: string @param deserialize_format: Format for de-serializing responses @type deserialize_format: string @param tenant_id: optional tenant id to be included in the header if given @type tenant_id: string
- def create_network(self, name=None, admin_state_up=None, shared=None, tenant_id=None, requestslib_kwargs=None): @summary: Creates a Network @param name: human readable name for the network, may not be unique. (CRUD: CRU) @type name: string @param admin_state_up: true or false, the admin state of the network. If down, the network does not forward packets. Default value is True (CRUD: CRU) @type admin_state_up: bool @param shared: specifies if the network can be accessed by any tenant. Default value is False. (CRUD: CRU) @type shared: bool @param tenant_id: owner of the network. (CRUD: CR) @type tenant_id: string @return: network create response @rtype: Requests.response
- def update_network(self, network_id, name=None, admin_state_up=None, shared=None, tenant_id=None, requestslib_kwargs=None): @summary: Updates a specified Network @param network_id: The UUID for the network @type network_id: string @param name: human readable name for the network, may not be unique. (CRUD: CRU) @type name: string @param admin_state_up: true or false, the admin state of the network. If down, the network does not forward packets. Default value is True (CRUD: CRU) @type admin_state_up: bool @param shared: specifies if the network can be accessed by any tenant. Default value is False. (CRUD: CRU) @type shared: bool @param tenant_id: owner of the network. (CRUD: CR) @type tenant_id: string @return: update network response @rtype: Requests.response
- def get_network(self, network_id, requestslib_kwargs=None): @summary: Shows information for a specified network @param network_id: The UUID for the network @type network_id: string @return: get network response @rtype: Requests.response
- def list_networks(self, network_id=None, name=None, status=None, admin_state_up=None, shared=None, tenant_id=None, limit=None, marker=None, page_reverse=None, requestslib_kwargs=None): @summary: Lists networks, filtered by params if given @param network_id: network ID to filter by @type network_id: string @param name: network name to filter by @type name: string @param status: network status to filter by @type status: string @param admin_state_up: Admin state of the network to filter by @type admin_state_up: bool @param shared: If network is shared across tenants status to filter by @type shared: bool @param tenant_id: tenant ID network owner to filter by @type tenant_id: string @param limit: page size @type limit: int @param marker: Id of the last item of the previous page @type marker: string @param page_reverse: direction of the page @type page_reverse: bool @return: li
- def delete_network(self, network_id, requestslib_kwargs=None): @summary: Deletes a specified network and its associated resources @param network_id: The UUID for the network @type network_id: string @return: delete network response @rtype: Requests.response

<|skeleton|>
class NetworksClient:

    def __init__(self, url, auth_token, serialize_format=None, deserialize_format=None, tenant_id=None):
        """@param url: Base URL for the networks service @type url: string @param auth_token: Auth token to be used for all requests @type auth_token: string @param serialize_format: Format for serializing requests @type serialize_format: string @param deserialize_format: Format for de-serializing responses @type deserialize_format: string @param tenant_id: optional tenant id to be included in the header if given @type tenant_id: string"""
        <|body_0|>

    def create_network(self, name=None, admin_state_up=None, shared=None, tenant_id=None, requestslib_kwargs=None):
        """@summary: Creates a Network @param name: human readable name for the network, may not be unique. (CRUD: CRU) @type name: string @param admin_state_up: true or false, the admin state of the network. If down, the network does not forward packets. Default value is True (CRUD: CRU) @type admin_state_up: bool @param shared: specifies if the network can be accessed by any tenant. Default value is False. (CRUD: CRU) @type shared: bool @param tenant_id: owner of the network. (CRUD: CR) @type tenant_id: string @return: network create response @rtype: Requests.response"""
        <|body_1|>

    def update_network(self, network_id, name=None, admin_state_up=None, shared=None, tenant_id=None, requestslib_kwargs=None):
        """@summary: Updates a specified Network @param network_id: The UUID for the network @type network_id: string @param name: human readable name for the network, may not be unique. (CRUD: CRU) @type name: string @param admin_state_up: true or false, the admin state of the network. If down, the network does not forward packets. Default value is True (CRUD: CRU) @type admin_state_up: bool @param shared: specifies if the network can be accessed by any tenant. Default value is False. (CRUD: CRU) @type shared: bool @param tenant_id: owner of the network. (CRUD: CR) @type tenant_id: string @return: update network response @rtype: Requests.response"""
        <|body_2|>

    def get_network(self, network_id, requestslib_kwargs=None):
        """@summary: Shows information for a specified network @param network_id: The UUID for the network @type network_id: string @return: get network response @rtype: Requests.response"""
        <|body_3|>

    def list_networks(self, network_id=None, name=None, status=None, admin_state_up=None, shared=None, tenant_id=None, limit=None, marker=None, page_reverse=None, requestslib_kwargs=None):
        """@summary: Lists networks, filtered by params if given @param network_id: network ID to filter by @type network_id: string @param name: network name to filter by @type name: string @param status: network status to filter by @type status: string @param admin_state_up: Admin state of the network to filter by @type admin_state_up: bool @param shared: If network is shared across tenants status to filter by @type shared: bool @param tenant_id: tenant ID network owner to filter by @type tenant_id: string @param limit: page size @type limit: int @param marker: Id of the last item of the previous page @type marker: string @param page_reverse: direction of the page @type page_reverse: bool @return: li"""
        <|body_4|>

    def delete_network(self, network_id, requestslib_kwargs=None):
        """@summary: Deletes a specified network and its associated resources @param network_id: The UUID for the network @type network_id: string @return: delete network response @rtype: Requests.response"""
        <|body_5|>

<|end_skeleton|>

<|body_start_0|>
        super(NetworksClient, self).__init__(serialize_format, deserialize_format)
        self.auth_token = auth_token
        self.default_headers['X-Auth-Token'] = auth_token
        ct = '{content_type}/{content_subtype}'.format(content_type='application', content_subtype=self.serialize_format)
        accept = '{content_type}/{content_subtype}'.format(content_type='application', content_subtype=self.deserialize_format)
        self.default_headers['Content-Type'] = ct
        self.default_headers['Accept'] = accept
        if tenant_id:
            self.default_headers['X-Auth-Project-Id'] = tenant_id
        self.url = url
<|end_body_0|>

<|body_start_1|>
        url = '{base_url}/networks'.format(base_url=self.url)
        request = NetworkRequest(name=name, admin_state_up=admin_state_up, shared=shared, tenant_id=tenant_id)
        resp = self.request('POST', url, response_entity_type=Network, request_entity=request, requestslib_kwargs=requestslib_kwargs)
        return resp
<|end_body_1|>

<|body_start_2|>
        url = '{base_url}/networks/{network_id}'.format(base_url=self.url, network_id=network_id)
        request = NetworkRequest(name=name, admin_state_up=admin_state_up, shared=shared, tenant_id=tenant_id)
        resp = self.request('PUT', url, response_entity_type=Network, request_entity=request, requestslib_kwargs=requestslib_kwargs)
        return resp
<|end_body_2|>

<|body_start_3|>
        url = '{base_url}/networks/{network_id}'.format(base_url=self.url, network_id=network_id)
        resp = self.request('GET', url, response_entity_type=Network, requestslib_kwargs=requestslib_kwargs)
        return resp
<|end_body_3|>

<|body_start_4|>
        params = {'id': network_id, 'name': name, 'status': status, 'admin_state_up': admin_state_up, 'shared': shared, 'tenant_id': tenant_id, 'limit': limit, 'marker': marker, 'page_reverse': page_reverse}
        url = '{base_url}/networks'.format(base_url=self.url)
        resp = self.request('GET', url, params=params, response_entity_type=Networks, requestslib_kwargs=requestslib_kwargs)
        return resp
<|end_body_4|>

<|body_start_5|>
        url = '{base_url}/networks/{network_id}'.format(base_url=self.url, network_id=network_id)
        resp = self.request('DELETE', url, requestslib_kwargs=requestslib_kwargs)
        return resp
<|end_body_5|>

Solution:
class NetworksClient:
    def __init__(self, url, auth_token, serialize_format=None, deserialize_format=None, tenant_id=None):
        """@param url: Base URL for the networks service @type url: string @param auth_token: Auth token to be used for all requests @type auth_token: string @param serialize_format: Format for serializing requests @type serialize_format: string @param deserialize_format: Format for de-serializing responses @type deserialize_format: string @param tenant_id: optional tenant id to be included in the header if given @type tenant_id: string"""
        super(NetworksClient, self).__init__(serialize_format, deserialize_format)
        self.auth_token = auth_token
        self.default_headers['X-Auth-Token'] = auth_token
        ct = '{content_type}/{content_subtype}'.format(content_type='application', content_subtype=self.serialize_format)
        accept = '{content_type}/{content_subtype}'.format(content_type='application', content_subtype=self.deserialize_format)
        self.default_headers['Content-Type'] = ct
        self.default_headers['Accept'] = accept
        if tenant_id:
            self.default_headers['X-Auth-Project-Id'] = tenant_id
        self.url = url

    def create_network(self, name=None, admin_state_up=None, shared=None, tenant_id=None, requestslib_kwargs=None):
        """@summary: Creates a Network @param name: human readable name for the network, may not be unique. (CRUD: CRU) @type name: string @param admin_state_up: true or false, the admin state of the network. If down, the network does not forward packets. Default value is True (CRUD: CRU) @type admin_state_up: bool @param shared: specifies if the network can be accessed by any tenant. Default value is False. (CRUD: CRU) @type shared: bool @param tenant_id: owner of the network. (CRUD: CR) @type tenant_id: string @return: network create response @rtype: Requests.response"""
        url = '{base_url}/networks'.format(base_url=self.url)
        request = NetworkRequest(name=name, admin_state_up=admin_state_up, shared=shared, tenant_id=tenant_id)
        resp = self.request('POST', url, response_entity_type=Network, request_entity=request, requestslib_kwargs=requestslib_kwargs)
        return resp

    def update_network(self, network_id, name=None, admin_state_up=None, shared=None, tenant_id=None, requestslib_kwargs=None):
        """@summary: Updates a specified Network @param network_id: The UUID for the network @type network_id: string @param name: human readable name for the network, may not be unique. (CRUD: CRU) @type name: string @param admin_state_up: true or false, the admin state of the network. If down, the network does not forward packets. Default value is True (CRUD: CRU) @type admin_state_up: bool @param shared: specifies if the network can be accessed by any tenant. Default value is False. (CRUD: CRU) @type shared: bool @param tenant_id: owner of the network. (CRUD: CR) @type tenant_id: string @return: update network response @rtype: Requests.response"""
        url = '{base_url}/networks/{network_id}'.format(base_url=self.url, network_id=network_id)
        request = NetworkRequest(name=name, admin_state_up=admin_state_up, shared=shared, tenant_id=tenant_id)
        resp = self.request('PUT', url, response_entity_type=Network, request_entity=request, requestslib_kwargs=requestslib_kwargs)
        return resp

    def get_network(self, network_id, requestslib_kwargs=None):
        """@summary: Shows information for a specified network @param network_id: The UUID for the network @type network_id: string @return: get network response @rtype: Requests.response"""
        url = '{base_url}/networks/{network_id}'.format(base_url=self.url, network_id=network_id)
        resp = self.request('GET', url, response_entity_type=Network, requestslib_kwargs=requestslib_kwargs)
        return resp

    def list_networks(self, network_id=None, name=None, status=None, admin_state_up=None, shared=None, tenant_id=None, limit=None, marker=None, page_reverse=None, requestslib_kwargs=None):
        """@summary: Lists networks, filtered by params if given @param network_id: network ID to filter by @type network_id: string @param name: network name to filter by @type name: string @param status: network status to filter by @type status: string @param admin_state_up: Admin state of the network to filter by @type admin_state_up: bool @param shared: If network is shared across tenants status to filter by @type shared: bool @param tenant_id: tenant ID network owner to filter by @type tenant_id: string @param limit: page size @type limit: int @param marker: Id of the last item of the previous page @type marker: string @param page_reverse: direction of the page @type page_reverse: bool @return: li"""
        params = {'id': network_id, 'name': name, 'status': status, 'admin_state_up': admin_state_up, 'shared': shared, 'tenant_id': tenant_id, 'limit': limit, 'marker': marker, 'page_reverse': page_reverse}
        url = '{base_url}/networks'.format(base_url=self.url)
        resp = self.request('GET', url, params=params, response_entity_type=Networks, requestslib_kwargs=requestslib_kwargs)
        return resp

    def delete_network(self, network_id, requestslib_kwargs=None):
        """@summary: Deletes a specified network and its associated resources @param network_id: The UUID for the network @type network_id: string @return: delete network response @rtype: Requests.response"""
        url = '{base_url}/networks/{network_id}'.format(base_url=self.url, network_id=network_id)
        resp = self.request('DELETE', url, requestslib_kwargs=requestslib_kwargs)
        return resp


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

Class description:
Form for uploading multiple files to a project. `subdir` is the project subdirectory relative to the file root.

Method signatures and docstrings:
- def clean_file_field(self): Check for file name, size limits and whether they are readable
- def perform_action(self): Upload the files

Implement the Python class `UploadFilesForm` described below.

Class description:
Form for uploading multiple files to a project. `subdir` is the project subdirectory relative to the file root.

Method signatures and docstrings:
- def clean_file_field(self): Check for file name, size limits and whether they are readable
- def perform_action(self): Upload the files

<|skeleton|>
class UploadFilesForm:
    """Form for uploading multiple files to a project. `subdir` is the project subdirectory relative to the file root."""

    def clean_file_field(self):
        """Check for file name, size limits and whether they are readable"""
        <|body_0|>

    def perform_action(self):
        """Upload the files"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        files = self.files.getlist('file_field')
        for file in files:
            validators.validate_filename(file.name)
            if not file:
                raise forms.ValidationError('Could not read file: %(file_name)s', params={'file_name': file.name})
        for file in files:
            if file.size > ActiveProject.INDIVIDUAL_FILE_SIZE_LIMIT:
                raise forms.ValidationError('File %(file_name)s is larger than the individual size limit: %(individual_size_limit)s', code='exceed_individual_limit', params={'file_name': file.name, 'individual_size_limit': utility.readable_size(ActiveProject.INDIVIDUAL_FILE_SIZE_LIMIT)})
        if sum((f.size for f in files)) > self.project.core_project.storage_allowance - self.project.storage_used():
            raise forms.ValidationError('Total upload volume exceeds remaining quota', code='exceed_remaining_quota')
        return files
<|end_body_0|>

<|body_start_1|>
        errors = ErrorList()
        for file in self.files.getlist('file_field'):
            try:
                utility.write_uploaded_file(file=file, overwrite=False, write_file_path=os.path.join(self.file_dir, file.name))
            except FileExistsError:
                errors.append(format_html('Item named {} already exists', file.name))
            except OSError:
                errors.append(format_html('Unable to upload {}', file.name))
        return ('Your files have been uploaded', errors)
<|end_body_1|>

Solution:
class UploadFilesForm:
    """Form for uploading multiple files to a project. `subdir` is the project subdirectory relative to the file root."""

    def clean_file_field(self):
        """Check for file name, size limits and whether they are readable"""
        files = self.files.getlist('file_field')
        for file in files:
            validators.validate_filename(file.name)
            if not file:
                raise forms.ValidationError('Could not read file: %(file_name)s', params={'file_name': file.name})
        for file in files:
            if file.size > ActiveProject.INDIVIDUAL_FILE_SIZE_LIMIT:
                raise forms.ValidationError('File %(file_name)s is larger than the individual size limit: %(individual_size_limit)s', code='exceed_individual_limit', params={'file_name': file.name, 'individual_size_limit': utility.readable_size(ActiveProject.INDIVIDUAL_FILE_SIZE_LIMIT)})
        if sum((f.size for f in files)) > self.project.core_project.storage_allowance - self.project.storage_used():
            raise forms.ValidationError('Total upload volume exceeds remaining quota', code='exceed_remaining_quota')
        return files

    def perform_action(self):
        """Upload the files"""
        errors = ErrorList()
        for file in self.files.getlist('file_field'):
            try:
                utility.write_uploaded_file(file=file, overwrite=False, write_file_path=os.path.join(self.file_dir, file.name))
            except FileExistsError:
                errors.append(format_html('Item named {} already exists', file.name))
            except OSError:
                errors.append(format_html('Unable to upload {}', file.name))
        return ('Your files have been uploaded', errors)


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

Class description:
Implement the HandEvaluator class.

Method signatures and docstrings:
- def card_to_str(card): Convert this card to a string or number for pypoker-eval. Note that I don't check whether you passed a Card or the right string format!
- def str_to_card(card_string): Convert this string to a pokerbots.engine.game.Card instance. Note that I don't check whether or not you passed the right format!
- def evaluate_hand(hand, board=[], iterations=1000): Return winning percentage of your hand, with ties counted as 0.5 Includes Monte-Carlo simulation of running the board. Includes trying all possible opponent hands. Arguments: hand: your hand board: the board if any iterations: number of times to simulate

Implement the Python class `HandEvaluator` described below.

Class description:
Implement the HandEvaluator class.

Method signatures and docstrings:
- def card_to_str(card): Convert this card to a string or number for pypoker-eval. Note that I don't check whether you passed a Card or the right string format!
- def str_to_card(card_string): Convert this string to a pokerbots.engine.game.Card instance. Note that I don't check whether or not you passed the right format!
- def evaluate_hand(hand, board=[], iterations=1000): Return winning percentage of your hand, with ties counted as 0.5 Includes Monte-Carlo simulation of running the board. Includes trying all possible opponent hands. Arguments: hand: your hand board: the board if any iterations: number of times to simulate

<|skeleton|>
class HandEvaluator:

    def card_to_str(card):
        """Convert this card to a string or number for pypoker-eval. Note that I don't check whether you passed a Card or the right string format!"""
        <|body_0|>

    def str_to_card(card_string):
        """Convert this string to a pokerbots.engine.game.Card instance. Note that I don't check whether or not you passed the right format!"""
        <|body_1|>

    def evaluate_hand(hand, board=[], iterations=1000):
        """Return winning percentage of your hand, with ties counted as 0.5 Includes Monte-Carlo simulation of running the board. Includes trying all possible opponent hands. Arguments: hand: your hand board: the board if any iterations: number of times to simulate"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        if isinstance(card, basestring):
            return card
        return card.__str__()
<|end_body_0|>

<|body_start_1|>
        if isinstance(card_string, Card):
            return card
        rank_str = card_string[0].lower()
        suit_str = card_string[1].lower()
        rank = 2
        suit = 1
        if rank_str == 't':
            rank = 10
        elif rank_str == 'j':
            rank = 11
        elif rank_str == 'q':
            rank = 12
        elif rank_str == 'k':
            rank = 13
        elif rank_str == 'a':
            rank = 14
        if suit_str == 's':
            suit = 1
        elif suit_str == 'h':
            suit = 2
        elif suit_str == 'd':
            suit = 3
        elif suit_str == 'c':
            suit = 4
        return Card(rank, suit)
<|end_body_1|>

<|body_start_2|>
        if len(board) == 5:
            hand = map(HandEvaluator.card_to_str, hand)
            board = map(HandEvaluator.card_to_str, board)
            poker_eval_result = HandEvaluator.evaluator.poker_eval(game='holdem', pockets=[hand, [255, 255]], dead=[], board=board)
        elif len(board) == 0:
            if hand[0].suit == hand[1].suit:
                return HandEvaluator.preflop_win_percentages_suited[hand[0].rank][hand[1].rank]
            else:
                return HandEvaluator.preflop_win_percentages_unsuited[hand[0].rank][hand[1].rank]
        else:
            hand = map(HandEvaluator.card_to_str, hand)
            board = map(HandEvaluator.card_to_str, board)
            for i in xrange(5 - len(board)):
                board.append(255)
            poker_eval_result = HandEvaluator.evaluator.poker_eval(game='holdem', pockets=[hand, [255, 255]], dead=[], board=board, iterations=iterations)
        return (poker_eval_result['eval'][0]['winhi'] + 0.5 * poker_eval_result['eval'][0]['tiehi']) / float(poker_eval_result['info'][0])
<|end_body_2|>

Solution:
class HandEvaluator:
    def card_to_str(card):
        """Convert this card to a string or number for pypoker-eval. Note that I don't check whether you passed a Card or the right string format!"""
        if isinstance(card, basestring):
            return card
        return card.__str__()

    def str_to_card(card_string):
        """Convert this string to a pokerbots.engine.game.Card instance. Note that I don't check whether or not you passed the right format!"""
        if isinstance(card_string, Card):
            return card
        rank_str = card_string[0].lower()
        suit_str = card_string[1].lower()
        rank = 2
        suit = 1
        if rank_str == 't':
            rank = 10
        elif rank_str == 'j':
            rank = 11
        elif rank_str == 'q':
            rank = 12
        elif rank_str == 'k':
            rank = 13
        elif rank_str == 'a':
            rank = 14
        if suit_str == 's':
            suit = 1
        elif suit_str == 'h':
            suit = 2
        elif suit_str == 'd':
            suit = 3
        elif suit_str == 'c':
            suit = 4
        return Card(rank, suit)

    def evaluate_hand(hand, board=[], iterations=1000):
        """Return winning percentage of your hand, with ties counted as 0.5 Includes Monte-Carlo simulation of running the board. Includes trying all possible opponent hands. Arguments: hand: your hand board: the board if any iterations: number of times to simulate"""
        if len(board) == 5:
            hand = map(HandEvaluator.card_to_str, hand)
            board = map(HandEvaluator.card_to_str, board)
            poker_eval_result = HandEvaluator.evaluator.poker_eval(game='holdem', pockets=[hand, [255, 255]], dead=[], board=board)
        elif len(board) == 0:
            if hand[0].suit == hand[1].suit:
                return HandEvaluator.preflop_win_percentages_suited[hand[0].rank][hand[1].rank]
            else:
                return HandEvaluator.preflop_win_percentages_unsuited[hand[0].rank][hand[1].rank]
        else:
            hand = map(HandEvaluator.card_to_str, hand)
            board = map(HandEvaluator.card_to_str, board)
            for i in xrange(5 - len(board)):
                board.append(255)
            poker_eval_result = HandEvaluator.evaluator.poker_eval(game='holdem', pockets=[hand, [255, 255]], dead=[], board=board, iterations=iterations)
        return (poker_eval_result['eval'][0]['winhi'] + 0.5 * poker_eval_result['eval'][0]['tiehi']) / float(poker_eval_result['info'][0])


findKthNumber

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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def findKthNumber(self, m, n, k): :type m: int :type n: int :type k: int :rtype: int
- def findKthNumber_1(self, m, n, k): :type m: int :type n: int :type k: int :rtype: int 1858ms
- def findKthNumber_2(self, m, n, k): :type m: int :type n: int :type k: int :rtype: int 477ms

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def findKthNumber(self, m, n, k): :type m: int :type n: int :type k: int :rtype: int
- def findKthNumber_1(self, m, n, k): :type m: int :type n: int :type k: int :rtype: int 1858ms
- def findKthNumber_2(self, m, n, k): :type m: int :type n: int :type k: int :rtype: int 477ms

<|skeleton|>
class Solution:

    def findKthNumber(self, m, n, k):
        """:type m: int :type n: int :type k: int :rtype: int"""
        <|body_0|>

    def findKthNumber_1(self, m, n, k):
        """:type m: int :type n: int :type k: int :rtype: int 1858ms"""
        <|body_1|>

    def findKthNumber_2(self, m, n, k):
        """:type m: int :type n: int :type k: int :rtype: int 477ms"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        import bisect

        def Count(num, m, n):
            count = 0
            ans = 0
            for i in range(1, m + 1):
                a = min(num // i, n)
                count += a
                ans = max(ans, a * i)
            return (count, ans)
        start, end = (1, m * n)
        result = []
        dicts = {}
        while start <= end:
            mid = (start + end) // 2
            c, ans = Count(mid, m, n)
            print(mid, c, ans)
            dicts[c] = ans
            result.append(c)
            if c > k:
                end = mid - 1
            elif c < k:
                start = mid + 1
            else:
                return ans
        a = sorted(result)
        pos = bisect.bisect_right(a, k)
        print(dicts)
        return dicts[a[pos]]
<|end_body_0|>

<|body_start_1|>
        def Count(num, m, n):
            count = 0
            ans = 0
            for i in range(1, m + 1):
                a = min(num // i, n)
                count += a
                ans = max(ans, a * i)
            return (count, ans)
        start, end = (1, m * n)
        while start < end:
            mid = (start + end) // 2
            c, ans = Count(mid, m, n)
            if c < k:
                start = mid + 1
            else:
                end = mid
        return start
<|end_body_1|>

<|body_start_2|>
        def countLessThan(x, m, n):
            assert m <= n
            count = 0
            for i in range(1, m + 1):
                if x // i < n:
                    count += x / i
                else:
                    count += n
            return count
        if m > n:
            m, n = (n, m)
        lo, hi = (1, m * n)
        while lo < hi:
            mid = (lo + hi) // 2
            if countLessThan(mid, m, n) < k:
                lo = mid + 1
            else:
                hi = mid
        return lo
<|end_body_2|>

Solution:
class Solution:
    def findKthNumber(self, m, n, k):
        """:type m: int :type n: int :type k: int :rtype: int"""
        import bisect

        def Count(num, m, n):
            count = 0
            ans = 0
            for i in range(1, m + 1):
                a = min(num // i, n)
                count += a
                ans = max(ans, a * i)
            return (count, ans)
        start, end = (1, m * n)
        result = []
        dicts = {}
        while start <= end:
            mid = (start + end) // 2
            c, ans = Count(mid, m, n)
            print(mid, c, ans)
            dicts[c] = ans
            result.append(c)
            if c > k:
                end = mid - 1
            elif c < k:
                start = mid + 1
            else:
                return ans
        a = sorted(result)
        pos = bisect.bisect_right(a, k)
        print(dicts)
        return dicts[a[pos]]

    def findKthNumber_1(self, m, n, k):
        """:type m: int :type n: int :type k: int :rtype: int 1858ms"""
        def Count(num, m, n):
            count = 0
            ans = 0
            for i in range(1, m + 1):
                a = min(num // i, n)
                count += a
                ans = max(ans, a * i)
            return (count, ans)
        start, end = (1, m * n)
        while start < end:
            mid = (start + end) // 2
            c, ans = Count(mid, m, n)
            if c < k:
                start = mid + 1
            else:
                end = mid
        return start

    def findKthNumber_2(self, m, n, k):
        """:type m: int :type n: int :type k: int :rtype: int 477ms"""
        def countLessThan(x, m, n):
            assert m <= n
            count = 0
            for i in range(1, m + 1):
                if x // i < n:
                    count += x / i
                else:
                    count += n
            return count
        if m > n:
            m, n = (n, m)
        lo, hi = (1, m * n)
        while lo < hi:
            mid = (lo + hi) // 2
            if countLessThan(mid, m, n) < k:
                lo = mid + 1
            else:
                hi = mid
        return lo


process

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

Class description:
Helper library for NISScan actor.

Method signatures and docstrings:
- def client_has_non_default_configuration(self): Check for any significant ypbind configuration lines in .conf file.
- def server_has_non_default_configuration(self): Check for any additional (not default) files in ypserv DIR.
- def process(self): Check NIS pkgs configuration for the following options: - yp.conf custom configuration - /var/yp not default entry

Implement the Python class `NISScanLibrary` described below.

Class description:
Helper library for NISScan actor.

Method signatures and docstrings:
- def client_has_non_default_configuration(self): Check for any significant ypbind configuration lines in .conf file.
- def server_has_non_default_configuration(self): Check for any additional (not default) files in ypserv DIR.
- def process(self): Check NIS pkgs configuration for the following options: - yp.conf custom configuration - /var/yp not default entry

<|skeleton|>
class NISScanLibrary:
    """Helper library for NISScan actor."""

    def client_has_non_default_configuration(self):
        """Check for any significant ypbind configuration lines in .conf file."""
        <|body_0|>

    def server_has_non_default_configuration(self):
        """Check for any additional (not default) files in ypserv DIR."""
        <|body_1|>

    def process(self):
        """Check NIS pkgs configuration for the following options: - yp.conf custom configuration - /var/yp not default entry"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        if not os.path.isfile(YPBIND_CONF_FILE):
            return False
        with open(YPBIND_CONF_FILE) as f:
            lines = [line.strip() for line in f.readlines() if line.strip()]
        for line in lines:
            if not line.startswith('#'):
                return True
        return False
<|end_body_0|>

<|body_start_1|>
        if not os.path.isdir(YPSERV_DIR_PATH):
            return False
        return any((f not in YPSERV_DEFAULT_FILES for f in os.listdir(YPSERV_DIR_PATH)))
<|end_body_1|>

<|body_start_2|>
        pkgs = []
        if self.server_has_non_default_configuration():
            pkgs.append('ypserv')
        if self.client_has_non_default_configuration():
            pkgs.append('ypbind')
        api.produce(NISConfig(nis_not_default_conf=pkgs))
<|end_body_2|>

Solution:
class NISScanLibrary:
    """Helper library for NISScan actor."""

    def client_has_non_default_configuration(self):
        """Check for any significant ypbind configuration lines in .conf file."""
        if not os.path.isfile(YPBIND_CONF_FILE):
            return False
        with open(YPBIND_CONF_FILE) as f:
            lines = [line.strip() for line in f.readlines() if line.strip()]
        for line in lines:
            if not line.startswith('#'):
                return True
        return False

    def server_has_non_default_configuration(self):
        """Check for any additional (not default) files in ypserv DIR."""
        if not os.path.isdir(YPSERV_DIR_PATH):
            return False
        return any((f not in YPSERV_DEFAULT_FILES for f in os.listdir(YPSERV_DIR_PATH)))

    def process(self):
        """Check NIS pkgs configuration for the following options: - yp.conf custom configuration - /var/yp not default entry"""
        pkgs = []
        if self.server_has_non_default_configuration():
            pkgs.append('ypserv')
        if self.client_has_non_default_configuration():
            pkgs.append('ypbind')
        api.produce(NISConfig(nis_not_default_conf=pkgs))


associate

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

Class description:
A country.

Method signatures and docstrings:
- def __init__(self, name: str, state: 'State'): :param name: the name of the state :param state: the state in which the county resides
- def associate(self, city: 'City', reflexive: bool=True): Associate this county with a city. :param city: the city which which the county is associated :param reflexive: if `True` the call will also attempt to create a back-reference to this county within the city

Implement the Python class `County` described below.

Class description:
A country.

Method signatures and docstrings:
- def __init__(self, name: str, state: 'State'): :param name: the name of the state :param state: the state in which the county resides
- def associate(self, city: 'City', reflexive: bool=True): Associate this county with a city. :param city: the city which which the county is associated :param reflexive: if `True` the call will also attempt to create a back-reference to this county within the city

<|skeleton|>
class County:
    """A country."""

    def __init__(self, name: str, state: 'State'):
        """:param name: the name of the state :param state: the state in which the county resides"""
        <|body_0|>

    def associate(self, city: 'City', reflexive: bool=True):
        """Associate this county with a city. :param city: the city which which the county is associated :param reflexive: if `True` the call will also attempt to create a back-reference to this county within the city"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.id: uuid.UUID = uuid.uuid4()
        self.state: 'State' = state
        self.name: str = name
        self._cities: Set['City'] = set()
<|end_body_0|>

<|body_start_1|>
        self._cities.add(city)
        if reflexive:
            city.associate(self, reflexive=False)
<|end_body_1|>

Solution:
class County:
    """A country."""

    def __init__(self, name: str, state: 'State'):
        """:param name: the name of the state :param state: the state in which the county resides"""
        self.id: uuid.UUID = uuid.uuid4()
        self.state: 'State' = state
        self.name: str = name
        self._cities: Set['City'] = set()

    def associate(self, city: 'City', reflexive: bool=True):
        """Associate this county with a city. :param city: the city which which the county is associated :param reflexive: if `True` the call will also attempt to create a back-reference to this county within the city"""
        self._cities.add(city)
        if reflexive:
            city.associate(self, reflexive=False)


list

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

Class description:
Implement the AccountView class.

Method signatures and docstrings:
- def get_queryset(self): Filter account by user pk :return: queryset
- def list(self, request, *args, **kwargs): Redeclared list method to return one instance :param request: :param args: :param kwargs: :return: Response()

Implement the Python class `AccountView` described below.

Class description:
Implement the AccountView class.

Method signatures and docstrings:
- def get_queryset(self): Filter account by user pk :return: queryset
- def list(self, request, *args, **kwargs): Redeclared list method to return one instance :param request: :param args: :param kwargs: :return: Response()

<|skeleton|>
class AccountView:

    def get_queryset(self):
        """Filter account by user pk :return: queryset"""
        <|body_0|>

    def list(self, request, *args, **kwargs):
        """Redeclared list method to return one instance :param request: :param args: :param kwargs: :return: Response()"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        user = self.request.user
        queryset = self.queryset.filter(pk=user.pk)
        return queryset
<|end_body_0|>

<|body_start_1|>
        try:
            account = self.get_queryset().get()
        except Exception:
            return Response(status=status.HTTP_404_NOT_FOUND)
        serializer = self.get_serializer(account)
        return Response(serializer.data)
<|end_body_1|>

Solution:
class AccountView:
    def get_queryset(self):
        """Filter account by user pk :return: queryset"""
        user = self.request.user
        queryset = self.queryset.filter(pk=user.pk)
        return queryset

    def list(self, request, *args, **kwargs):
        """Redeclared list method to return one instance :param request: :param args: :param kwargs: :return: Response()"""
        try:
            account = self.get_queryset().get()
        except Exception:
            return Response(status=status.HTTP_404_NOT_FOUND)
        serializer = self.get_serializer(account)
        return Response(serializer.data)


interpreter

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

Class description:
Commande 'meteo créer'

Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre.
- def interpreter(self, personnage, dic_masques): Méthode d'interprétation de commande

Implement the Python class `PrmCreer` described below.

Class description:
Commande 'meteo créer'

Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre.
- def interpreter(self, personnage, dic_masques): Méthode d'interprétation de commande

<|skeleton|>
class PrmCreer:
    """Commande 'meteo créer'"""

    def __init__(self):
        """Constructeur du paramètre."""
        <|body_0|>

    def interpreter(self, personnage, dic_masques):
        """Méthode d'interprétation de commande"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        Parametre.__init__(self, 'creer', 'create')
        self.schema = '(<cle>)'
        self.aide_courte = 'crée une perturbation'
        self.aide_longue = "Cette commande permet de créer une perturbation météorologique dans la salle où vous vous trouvez (par exemple, faire apparaître un nuage). La salle où vous vous trouvez est prise comme point de départ. Notez que vous ne pourrez pas faire apparaître une perturbation si une autre est présente ou trop proche. Les perturbations ont en effet des rayons d'action, et deux perturbations ne doivent pas entrer en conflit (un nuage ne doit pas en recouvrir un second, par exemple). Si vous ne savez pas quelles perturbations sont disponibles, entrez la commande sans paramètre."
<|end_body_0|>

<|body_start_1|>
        if dic_masques['cle']:
            cle = dic_masques['cle'].cle
            classe = None
            for t_classe in importeur.meteo.perturbations:
                if t_classe.nom_pertu == cle and t_classe.origine:
                    classe = t_classe
                    break
            if classe is None:
                personnage << "|err|Cette perturbation n'existe pas.|ff|"
                return
            if not personnage.salle.coords.valide:
                personnage << '|err|Vous vous trouvez dans une salle sans coordonnées.|ff|'
                return
            n_pertu = classe(personnage.salle.coords.get_copie())
            for pertu in importeur.meteo.perturbations_actuelles:
                if n_pertu.va_recouvrir(pertu):
                    personnage << '|err|Une autre perturbation est trop proche de vous.|ff|'
                    n_pertu.detruire()
                    return
            personnage << 'Vous avez bien créé une nouvelle perturbation {}.'.format(n_pertu.nom_pertu)
            importeur.meteo.perturbations_actuelles.append(n_pertu)
            n_pertu.envoyer_message_debut()
        else:
            tableau = Tableau('Perturbations existantes')
            tableau.ajouter_colonne('Clé')
            tableau.ajouter_colonne('Attributs')
            for perturbation in sorted(importeur.meteo.perturbations, key=lambda p: p.nom_pertu):
                attributs = ', '.join(perturbation.attributs)
                tableau.ajouter_ligne(perturbation.nom_pertu, attributs)
            personnage << tableau.afficher()
<|end_body_1|>

Solution:
class PrmCreer:
    """Commande 'meteo créer'"""

    def __init__(self):
        """Constructeur du paramètre."""
        Parametre.__init__(self, 'creer', 'create')
        self.schema = '(<cle>)'
        self.aide_courte = 'crée une perturbation'
        self.aide_longue = "Cette commande permet de créer une perturbation météorologique dans la salle où vous vous trouvez (par exemple, faire apparaître un nuage). La salle où vous vous trouvez est prise comme point de départ. Notez que vous ne pourrez pas faire apparaître une perturbation si une autre est présente ou trop proche. Les perturbations ont en effet des rayons d'action, et deux perturbations ne doivent pas entrer en conflit (un nuage ne doit pas en recouvrir un second, par exemple). Si vous ne savez pas quelles perturbations sont disponibles, entrez la commande sans paramètre."

    def interpreter(self, personnage, dic_masques):
        """Méthode d'interprétation de commande"""
        if dic_masques['cle']:
            cle = dic_masques['cle'].cle
            classe = None
            for t_classe in importeur.meteo.perturbations:
                if t_classe.nom_pertu == cle and t_classe.origine:
                    classe = t_classe
                    break
            if classe is None:
                personnage << "|err|Cette perturbation n'existe pas.|ff|"
                return
            if not personnage.salle.coords.valide:
                personnage << '|err|Vous vous trouvez dans une salle sans coordonnées.|ff|'
                return
            n_pertu = classe(personnage.salle.coords.get_copie())
            for pertu in importeur.meteo.perturbations_actuelles:
                if n_pertu.va_recouvrir(pertu):
                    personnage << '|err|Une autre perturbation est trop proche de vous.|ff|'
                    n_pertu.detruire()
                    return
            personnage << 'Vous avez bien créé une nouvelle perturbation {}.'.format(n_pertu.nom_pertu)
            importeur.meteo.perturbations_actuelles.append(n_pertu)
            n_pertu.envoyer_message_debut()
        else:
            tableau = Tableau('Perturbations existantes')
            tableau.ajouter_colonne('Clé')
            tableau.ajouter_colonne('Attributs')
            for perturbation in sorted(importeur.meteo.perturbations, key=lambda p: p.nom_pertu):
                attributs = ', '.join(perturbation.attributs)
                tableau.ajouter_ligne(perturbation.nom_pertu, attributs)
            personnage << tableau.afficher()


plusOne

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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def plusOne(self, digits): :type digits: List[int] :rtype: List[int] 正序计算
- def plusOne2(self, digits): :type digits: List[int] :rtype: List[int] 反转数组，从左往右计算 反转后第一位+1小于10，则+1即可退出循环 反转后第一位+1=10，则当前位=0，继续循环；最后一位时直接=0且最后增加一位1
- def plusOne3(self, digits): :type digits: List[int] :rtype: List[int] 类型转换的方法

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def plusOne(self, digits): :type digits: List[int] :rtype: List[int] 正序计算
- def plusOne2(self, digits): :type digits: List[int] :rtype: List[int] 反转数组，从左往右计算 反转后第一位+1小于10，则+1即可退出循环 反转后第一位+1=10，则当前位=0，继续循环；最后一位时直接=0且最后增加一位1
- def plusOne3(self, digits): :type digits: List[int] :rtype: List[int] 类型转换的方法

<|skeleton|>
class Solution:

    def plusOne(self, digits):
        """:type digits: List[int] :rtype: List[int] 正序计算"""
        <|body_0|>

    def plusOne2(self, digits):
        """:type digits: List[int] :rtype: List[int] 反转数组，从左往右计算 反转后第一位+1小于10，则+1即可退出循环 反转后第一位+1=10，则当前位=0，继续循环；最后一位时直接=0且最后增加一位1"""
        <|body_1|>

    def plusOne3(self, digits):
        """:type digits: List[int] :rtype: List[int] 类型转换的方法"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        digits = digits[::-1]
        print(digits)
        l = len(digits)
        p = l - 1
        f = False
        while p >= 0:
            if digits[p] != 9:
                digits[p] += 1
                if f == True or p == l - 1:
                    return digits
            else:
                f = True
                digits[p] = 0
                p -= 1
                if p == -1:
                    digits.insert(0, 1)
                    return digits
<|end_body_0|>

<|body_start_1|>
        length = len(digits)
        digits = digits[::-1]
        for i in range(length):
            if digits[i] + 1 < 10:
                digits[i] = digits[i] + 1
                break
            elif i != length - 1:
                digits[i] = 0
            else:
                digits[i] = 0
                digits.append(1)
        digits = digits[::-1]
        return digits
<|end_body_1|>

<|body_start_2|>
        s = ''
        for i in digits:
            s += str(i)
        s = int(s)
        s += 1
        s = str(s)
        digits = []
        for i in s:
            digits.append(int(i))
        return digits
<|end_body_2|>

Solution:
class Solution:
    def plusOne(self, digits):
        """:type digits: List[int] :rtype: List[int] 正序计算"""
        digits = digits[::-1]
        print(digits)
        l = len(digits)
        p = l - 1
        f = False
        while p >= 0:
            if digits[p] != 9:
                digits[p] += 1
                if f == True or p == l - 1:
                    return digits
            else:
                f = True
                digits[p] = 0
                p -= 1
                if p == -1:
                    digits.insert(0, 1)
                    return digits

    def plusOne2(self, digits):
        """:type digits: List[int] :rtype: List[int] 反转数组，从左往右计算 反转后第一位+1小于10，则+1即可退出循环 反转后第一位+1=10，则当前位=0，继续循环；最后一位时直接=0且最后增加一位1"""
        length = len(digits)
        digits = digits[::-1]
        for i in range(length):
            if digits[i] + 1 < 10:
                digits[i] = digits[i] + 1
                break
            elif i != length - 1:
                digits[i] = 0
            else:
                digits[i] = 0
                digits.append(1)
        digits = digits[::-1]
        return digits

    def plusOne3(self, digits):
        """:type digits: List[int] :rtype: List[int] 类型转换的方法"""
        s = ''
        for i in digits:
            s += str(i)
        s = int(s)
        s += 1
        s = str(s)
        digits = []
        for i in s:
            digits.append(int(i))
        return digits


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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def max_profit(self, prices): The meaning of dp[i] is the maximum profit of selling the stock at i-th day. And the stock has to be bought on or before that day. dp[i+1] is max(dp[i] + (prices[i+1] - prices[i]), 0). This is because the sell day is fixed and bought day must be the same as bought day of dp[i]. However, if this value is less than zero, we would rather buy and sell on the (i+1)-th day, to make the profit equal to 1.
- def max_profit_min_price(self, prices): The idea is to maintain the min_price and max_profit, the update rule for max_profit is max(max_profit, current_price - min_price)

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def max_profit(self, prices): The meaning of dp[i] is the maximum profit of selling the stock at i-th day. And the stock has to be bought on or before that day. dp[i+1] is max(dp[i] + (prices[i+1] - prices[i]), 0). This is because the sell day is fixed and bought day must be the same as bought day of dp[i]. However, if this value is less than zero, we would rather buy and sell on the (i+1)-th day, to make the profit equal to 1.
- def max_profit_min_price(self, prices): The idea is to maintain the min_price and max_profit, the update rule for max_profit is max(max_profit, current_price - min_price)

<|skeleton|>
class Solution:

    def max_profit(self, prices):
        """The meaning of dp[i] is the maximum profit of selling the stock at i-th day. And the stock has to be bought on or before that day. dp[i+1] is max(dp[i] + (prices[i+1] - prices[i]), 0). This is because the sell day is fixed and bought day must be the same as bought day of dp[i]. However, if this value is less than zero, we would rather buy and sell on the (i+1)-th day, to make the profit equal to 1."""
        <|body_0|>

    def max_profit_min_price(self, prices):
        """The idea is to maintain the min_price and max_profit, the update rule for max_profit is max(max_profit, current_price - min_price)"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        if not prices:
            return 0
        pre = 0
        opt_profit = 0
        for i in range(1, len(prices)):
            pre = max(pre + (prices[i] - prices[i - 1]), 0)
            opt_profit = max(opt_profit, pre)
        return opt_profit
<|end_body_0|>

<|body_start_1|>
        if not prices:
            return 0
        min_price = float('inf')
        opt = 0
        for price in prices:
            min_price = min(price, min_price)
            opt = max(opt, price - min_price)
        return opt
<|end_body_1|>

Solution:
class Solution:
    def max_profit(self, prices):
        """The meaning of dp[i] is the maximum profit of selling the stock at i-th day. And the stock has to be bought on or before that day. dp[i+1] is max(dp[i] + (prices[i+1] - prices[i]), 0). This is because the sell day is fixed and bought day must be the same as bought day of dp[i]. However, if this value is less than zero, we would rather buy and sell on the (i+1)-th day, to make the profit equal to 1."""
        if not prices:
            return 0
        pre = 0
        opt_profit = 0
        for i in range(1, len(prices)):
            pre = max(pre + (prices[i] - prices[i - 1]), 0)
            opt_profit = max(opt_profit, pre)
        return opt_profit

    def max_profit_min_price(self, prices):
        """The idea is to maintain the min_price and max_profit, the update rule for max_profit is max(max_profit, current_price - min_price)"""
        if not prices:
            return 0
        min_price = float('inf')
        opt = 0
        for price in prices:
            min_price = min(price, min_price)
            opt = max(opt, price - min_price)
        return opt


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

Class description:
Record the announcement info. :url /announcement

Method signatures and docstrings:
- def post(self): Insert new items.
- def delete(self): Delete announcement.

Implement the Python class `AnnouncementHandler` described below.

Class description:
Record the announcement info. :url /announcement

Method signatures and docstrings:
- def post(self): Insert new items.
- def delete(self): Delete announcement.

<|skeleton|>
class AnnouncementHandler:
    """Record the announcement info. :url /announcement"""

    def post(self):
        """Insert new items."""
        <|body_0|>

    def delete(self):
        """Delete announcement."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        status = ErrorCode.SUCCESS
        try:
            data = DotDict(json_decode(self.request.body))
            content = data.get('content', '')
            mobiles = data.get('mobiles', None)
            logging.info('[UWEB] Announcement request: %s', data)
        except Exception as e:
            status = ErrorCode.ILLEGAL_DATA_FORMAT
            self.write_ret(status)
            return
        try:
            mobiles_ = u''
            if mobiles is not None:
                mobiles_ = ','.join(mobiles)
                for mobile in mobiles:
                    SMSHelper.send(mobile, content)
            announcement = dict(cid=self.current_user.cid, content=content, mobiles=mobiles_)
            record_announcement(self.db, announcement)
            self.write_ret(status)
        except Exception as e:
            status = ErrorCode.SERVER_BUSY
            logging.exception('[UWEB] record share failed, Exception: %s', e.args)
            self.write_ret(status)
<|end_body_0|>

<|body_start_1|>
        status = ErrorCode.SUCCESS
        try:
            delete_ids = map(int, str_to_list(self.get_argument('ids', None)))
            logging.info('[UWEB] Delete announcement: %s', delete_ids)
        except Exception as e:
            status = ErrorCode.ILLEGAL_DATA_FORMAT
            logging.exception('[UWEB] data format illegal. Exception: %s', e.args)
            self.write_ret(status)
            return
        try:
            self.db.execute('DELETE FROM T_ANNOUNCEMENT_LOG WHERE id IN %s', tuple(delete_ids + DUMMY_IDS))
            self.write_ret(status)
        except Exception as e:
            status = ErrorCode.SERVER_BUSY
            logging.exception('[UWEB] Delete announcement failed. Exception: %s', e.args)
            self.write_ret(status)
<|end_body_1|>

Solution:
class AnnouncementHandler:
    """Record the announcement info. :url /announcement"""

    def post(self):
        """Insert new items."""
        status = ErrorCode.SUCCESS
        try:
            data = DotDict(json_decode(self.request.body))
            content = data.get('content', '')
            mobiles = data.get('mobiles', None)
            logging.info('[UWEB] Announcement request: %s', data)
        except Exception as e:
            status = ErrorCode.ILLEGAL_DATA_FORMAT
            self.write_ret(status)
            return
        try:
            mobiles_ = u''
            if mobiles is not None:
                mobiles_ = ','.join(mobiles)
                for mobile in mobiles:
                    SMSHelper.send(mobile, content)
            announcement = dict(cid=self.current_user.cid, content=content, mobiles=mobiles_)
            record_announcement(self.db, announcement)
            self.write_ret(status)
        except Exception as e:
            status = ErrorCode.SERVER_BUSY
            logging.exception('[UWEB] record share failed, Exception: %s', e.args)
            self.write_ret(status)

    def delete(self):
        """Delete announcement."""
        status = ErrorCode.SUCCESS
        try:
            delete_ids = map(int, str_to_list(self.get_argument('ids', None)))
            logging.info('[UWEB] Delete announcement: %s', delete_ids)
        except Exception as e:
            status = ErrorCode.ILLEGAL_DATA_FORMAT
            logging.exception('[UWEB] data format illegal. Exception: %s', e.args)
            self.write_ret(status)
            return
        try:
            self.db.execute('DELETE FROM T_ANNOUNCEMENT_LOG WHERE id IN %s', tuple(delete_ids + DUMMY_IDS))
            self.write_ret(status)
        except Exception as e:
            status = ErrorCode.SERVER_BUSY
            logging.exception('[UWEB] Delete announcement failed. Exception: %s', e.args)
            self.write_ret(status)


forward

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

Class description:
TransformerEncoder is a stack of N encoder layers.

Method signatures and docstrings:
- def __init__(self, input_size: int=512, d_model: int=512, nhead: int=8, num_layers: int=6, dim_feedforward: int=2048, dropout: float=0.1) -> None: Initialize the TransformerEncoder. Parameters --------- input_size : int The embedding dimension of the model. If different from d_model, a linear projection layer is added. d_model : int the number of expected features in encoder/decoder inputs. Default ``512``. nhead : int, optional the number of heads in the multiheadattention Default ``8``. num_layers : int the number of sub-encoder-layers in the encoder (required). Default ``6``. dim_feedforward : int, optional the inner feedforard dimension. Default ``2048``. dropout : float, optional the dropout percentage. Default ``0.1``.
- def forward(self, src: torch.Tensor, memory: Optional[torch.Tensor]=None, mask: Optional[torch.Tensor]=None, padding_mask: Optional[torch.Tensor]=None) -> torch.Tensor: Pass the input through the endocder layers in turn. Parameters ---------- src: torch.Tensor The sequence to the encoder (required). memory: torch.Tensor, optional Optional memory, unused by default. mask: torch.Tensor, optional The mask for the src sequence (optional). padding_mask: torch.Tensor, optional The mask for the src keys per batch (optional). Should be True for tokens to leave untouched, and False for padding tokens.
- def _reset_parameters(self): Initiate parameters in the transformer model.

Implement the Python class `TransformerEncoder` described below.

Class description:
TransformerEncoder is a stack of N encoder layers.

Method signatures and docstrings:
- def __init__(self, input_size: int=512, d_model: int=512, nhead: int=8, num_layers: int=6, dim_feedforward: int=2048, dropout: float=0.1) -> None: Initialize the TransformerEncoder. Parameters --------- input_size : int The embedding dimension of the model. If different from d_model, a linear projection layer is added. d_model : int the number of expected features in encoder/decoder inputs. Default ``512``. nhead : int, optional the number of heads in the multiheadattention Default ``8``. num_layers : int the number of sub-encoder-layers in the encoder (required). Default ``6``. dim_feedforward : int, optional the inner feedforard dimension. Default ``2048``. dropout : float, optional the dropout percentage. Default ``0.1``.
- def forward(self, src: torch.Tensor, memory: Optional[torch.Tensor]=None, mask: Optional[torch.Tensor]=None, padding_mask: Optional[torch.Tensor]=None) -> torch.Tensor: Pass the input through the endocder layers in turn. Parameters ---------- src: torch.Tensor The sequence to the encoder (required). memory: torch.Tensor, optional Optional memory, unused by default. mask: torch.Tensor, optional The mask for the src sequence (optional). padding_mask: torch.Tensor, optional The mask for the src keys per batch (optional). Should be True for tokens to leave untouched, and False for padding tokens.
- def _reset_parameters(self): Initiate parameters in the transformer model.

<|skeleton|>
class TransformerEncoder:
    """TransformerEncoder is a stack of N encoder layers."""

    def __init__(self, input_size: int=512, d_model: int=512, nhead: int=8, num_layers: int=6, dim_feedforward: int=2048, dropout: float=0.1) -> None:
        """Initialize the TransformerEncoder. Parameters --------- input_size : int The embedding dimension of the model. If different from d_model, a linear projection layer is added. d_model : int the number of expected features in encoder/decoder inputs. Default ``512``. nhead : int, optional the number of heads in the multiheadattention Default ``8``. num_layers : int the number of sub-encoder-layers in the encoder (required). Default ``6``. dim_feedforward : int, optional the inner feedforard dimension. Default ``2048``. dropout : float, optional the dropout percentage. Default ``0.1``."""
        <|body_0|>

    def forward(self, src: torch.Tensor, memory: Optional[torch.Tensor]=None, mask: Optional[torch.Tensor]=None, padding_mask: Optional[torch.Tensor]=None) -> torch.Tensor:
        """Pass the input through the endocder layers in turn. Parameters ---------- src: torch.Tensor The sequence to the encoder (required). memory: torch.Tensor, optional Optional memory, unused by default. mask: torch.Tensor, optional The mask for the src sequence (optional). padding_mask: torch.Tensor, optional The mask for the src keys per batch (optional). Should be True for tokens to leave untouched, and False for padding tokens."""
        <|body_1|>

    def _reset_parameters(self):
        """Initiate parameters in the transformer model."""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        super().__init__()
        self.input_size = input_size
        self.d_model = d_model
        if input_size != d_model:
            self.proj = nn.Linear(input_size, d_model)
        layer = TransformerEncoderLayer(d_model, nhead, dim_feedforward, dropout)
        self.layers = nn.ModuleList([copy.deepcopy(layer) for _ in range(num_layers)])
        self.num_layers = num_layers
        self._reset_parameters()
<|end_body_0|>

<|body_start_1|>
        output = src.transpose(0, 1)
        if self.input_size != self.d_model:
            output = self.proj(output)
        for i in range(self.num_layers):
            output = self.layers[i](output, memory=memory, src_mask=mask, padding_mask=padding_mask)
        return output.transpose(0, 1)
<|end_body_1|>

<|body_start_2|>
        for p in self.parameters():
            if p.dim() > 1:
                nn.init.xavier_uniform_(p)
<|end_body_2|>

Solution:
class TransformerEncoder:
    """TransformerEncoder is a stack of N encoder layers."""

    def __init__(self, input_size: int=512, d_model: int=512, nhead: int=8, num_layers: int=6, dim_feedforward: int=2048, dropout: float=0.1) -> None:
        """Initialize the TransformerEncoder. Parameters --------- input_size : int The embedding dimension of the model. If different from d_model, a linear projection layer is added. d_model : int the number of expected features in encoder/decoder inputs. Default ``512``. nhead : int, optional the number of heads in the multiheadattention Default ``8``. num_layers : int the number of sub-encoder-layers in the encoder (required). Default ``6``. dim_feedforward : int, optional the inner feedforard dimension. Default ``2048``. dropout : float, optional the dropout percentage. Default ``0.1``."""
        super().__init__()
        self.input_size = input_size
        self.d_model = d_model
        if input_size != d_model:
            self.proj = nn.Linear(input_size, d_model)
        layer = TransformerEncoderLayer(d_model, nhead, dim_feedforward, dropout)
        self.layers = nn.ModuleList([copy.deepcopy(layer) for _ in range(num_layers)])
        self.num_layers = num_layers
        self._reset_parameters()

    def forward(self, src: torch.Tensor, memory: Optional[torch.Tensor]=None, mask: Optional[torch.Tensor]=None, padding_mask: Optional[torch.Tensor]=None) -> torch.Tensor:
        """Pass the input through the endocder layers in turn. Parameters ---------- src: torch.Tensor The sequence to the encoder (required). memory: torch.Tensor, optional Optional memory, unused by default. mask: torch.Tensor, optional The mask for the src sequence (optional). padding_mask: torch.Tensor, optional The mask for the src keys per batch (optional). Should be True for tokens to leave untouched, and False for padding tokens."""
        output = src.transpose(0, 1)
        if self.input_size != self.d_model:
            output = self.proj(output)
        for i in range(self.num_layers):
            output = self.layers[i](output, memory=memory, src_mask=mask, padding_mask=padding_mask)
        return output.transpose(0, 1)

    def _reset_parameters(self):
        """Initiate parameters in the transformer model."""
        for p in self.parameters():
            if p.dim() > 1:
                nn.init.xavier_uniform_(p)


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

Class description:
Implementation of the 'MetricValue' model. Specifies one data point of a metric. Attributes: metric_name (string): Specifies the metric name. timestamp_msecs (long|int): Specifies the creation time of a data point as a Unix epoch Timestamp (in milliseconds). value (Value): Specifies the value of the data point.

Method signatures and docstrings:
- def __init__(self, metric_name=None, timestamp_msecs=None, value=None): Constructor for the MetricValue class
- def from_dictionary(cls, dictionary): Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obtained from the deserialization of the server's response. The keys MUST match property names in the API description. Returns: object: An instance of this structure class.

Implement the Python class `MetricValue` described below.

Class description:
Implementation of the 'MetricValue' model. Specifies one data point of a metric. Attributes: metric_name (string): Specifies the metric name. timestamp_msecs (long|int): Specifies the creation time of a data point as a Unix epoch Timestamp (in milliseconds). value (Value): Specifies the value of the data point.

Method signatures and docstrings:
- def __init__(self, metric_name=None, timestamp_msecs=None, value=None): Constructor for the MetricValue class
- def from_dictionary(cls, dictionary): Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obtained from the deserialization of the server's response. The keys MUST match property names in the API description. Returns: object: An instance of this structure class.

<|skeleton|>
class MetricValue:
    """Implementation of the 'MetricValue' model. Specifies one data point of a metric. Attributes: metric_name (string): Specifies the metric name. timestamp_msecs (long|int): Specifies the creation time of a data point as a Unix epoch Timestamp (in milliseconds). value (Value): Specifies the value of the data point."""

    def __init__(self, metric_name=None, timestamp_msecs=None, value=None):
        """Constructor for the MetricValue class"""
        <|body_0|>

    def from_dictionary(cls, dictionary):
        """Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obtained from the deserialization of the server's response. The keys MUST match property names in the API description. Returns: object: An instance of this structure class."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.metric_name = metric_name
        self.timestamp_msecs = timestamp_msecs
        self.value = value
<|end_body_0|>

<|body_start_1|>
        if dictionary is None:
            return None
        metric_name = dictionary.get('metricName')
        timestamp_msecs = dictionary.get('timestampMsecs')
        value = cohesity_management_sdk.models.value.Value.from_dictionary(dictionary.get('value')) if dictionary.get('value') else None
        return cls(metric_name, timestamp_msecs, value)
<|end_body_1|>

Solution:
class MetricValue:
    """Implementation of the 'MetricValue' model. Specifies one data point of a metric. Attributes: metric_name (string): Specifies the metric name. timestamp_msecs (long|int): Specifies the creation time of a data point as a Unix epoch Timestamp (in milliseconds). value (Value): Specifies the value of the data point."""

    def __init__(self, metric_name=None, timestamp_msecs=None, value=None):
        """Constructor for the MetricValue class"""
        self.metric_name = metric_name
        self.timestamp_msecs = timestamp_msecs
        self.value = value

    def from_dictionary(cls, dictionary):
        """Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obtained from the deserialization of the server's response. The keys MUST match property names in the API description. Returns: object: An instance of this structure class."""
        if dictionary is None:
            return None
        metric_name = dictionary.get('metricName')
        timestamp_msecs = dictionary.get('timestampMsecs')
        value = cohesity_management_sdk.models.value.Value.from_dictionary(dictionary.get('value')) if dictionary.get('value') else None
        return cls(metric_name, timestamp_msecs, value)


deserialize

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

Class description:
Implement the Codec class.

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

Implement the Python class `Codec` described below.

Class description:
Implement the Codec class.

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

<|skeleton|>
class Codec:

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

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

<|end_skeleton|>

<|body_start_0|>
        if root is None:
            return ''
        q = []

        def preorder(root):
            if root is None:
                return None
            else:
                q.append(root.val)
                for child in (root, children):
                    preorder(child)
                q.append('#')
        preorder(root)
        return ','.join(map(str, q))
<|end_body_0|>

<|body_start_1|>
        if data == '':
            return None
        data = deque(data.split(','))
        root = Node(int(data.popleft()), [])

        def solve(root):
            val = data.popleft()
            while val != '#':
                child = Node(int(val, []))
                solve(child)
                root.children.append(child)
                val = data.popleft()
        solve(root)
        return root
<|end_body_1|>

Solution:
class Codec:
    def serialize(self, root):
        """Encodes a tree to a single string. :type root: Node :rtype: str"""
        if root is None:
            return ''
        q = []

        def preorder(root):
            if root is None:
                return None
            else:
                q.append(root.val)
                for child in (root, children):
                    preorder(child)
                q.append('#')
        preorder(root)
        return ','.join(map(str, q))

    def deserialize(self, data):
        """Decodes your encoded data to tree. :type data: str :rtype: Node"""
        if data == '':
            return None
        data = deque(data.split(','))
        root = Node(int(data.popleft()), [])

        def solve(root):
            val = data.popleft()
            while val != '#':
                child = Node(int(val, []))
                solve(child)
                root.children.append(child)
                val = data.popleft()
        solve(root)
        return root

archive/428. Serialize and Deserialize N-ary Tree.py


get

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

Class description:
Implement the PathMapIndexAPI class.

Method signatures and docstrings:
- def post(self): A ``POST`` to this endpoint will create a new path map. A path map will list the equivalent path prefixes for all three supported families of operating systems, Linux, Windows and OS X. A path map can optionally be restricted to one tag, in which case it will only apply to agents with that tag. If a tag is specified that does not exist yet, that tag will be transparently created. .. http:post:: /api/v1/pathmaps/ HTTP/1.1 **Request** .. sourcecode:: http POST /api/v1/pathmaps/ HTTP/1.1 Accept: application/json { "path_linux": "/mnt/nfs", "path_windows": "\\domain\\cifs_server", "path_osx": "/mnt/nfs", "tag": "production" } **Response** .. sourcecode:: http HTTP/1.1 201 CREATED Content-Type: a
- def get(self): A ``GET`` to this endpoint will return a list of all registered path maps, with id. It can be made with a for_agent query parameter, in which case it will return only those path maps that apply to that agent. .. http:get:: /api/v1/pathmaps/ HTTP/1.1 **Request** .. sourcecode:: http GET /api/v1/pathmaps/ HTTP/1.1 Accept: application/json **Response** .. sourcecode:: http HTTP/1.1 200 OK Content-Type: application/json [ { "id": 1, "path_osx": "/mnt/nfs", "path_windows": "\\\\domains\\cifs_server", "path_linux": "/mnt/nfs" }, { "id": 7, "path_osx": "/renderout", "path_windows": "c:\\renderout", "path_linux": "/renderout" "tag": "usual", } ] :statuscode 200: no error

Implement the Python class `PathMapIndexAPI` described below.

Class description:
Implement the PathMapIndexAPI class.

Method signatures and docstrings:
- def post(self): A ``POST`` to this endpoint will create a new path map. A path map will list the equivalent path prefixes for all three supported families of operating systems, Linux, Windows and OS X. A path map can optionally be restricted to one tag, in which case it will only apply to agents with that tag. If a tag is specified that does not exist yet, that tag will be transparently created. .. http:post:: /api/v1/pathmaps/ HTTP/1.1 **Request** .. sourcecode:: http POST /api/v1/pathmaps/ HTTP/1.1 Accept: application/json { "path_linux": "/mnt/nfs", "path_windows": "\\domain\\cifs_server", "path_osx": "/mnt/nfs", "tag": "production" } **Response** .. sourcecode:: http HTTP/1.1 201 CREATED Content-Type: a
- def get(self): A ``GET`` to this endpoint will return a list of all registered path maps, with id. It can be made with a for_agent query parameter, in which case it will return only those path maps that apply to that agent. .. http:get:: /api/v1/pathmaps/ HTTP/1.1 **Request** .. sourcecode:: http GET /api/v1/pathmaps/ HTTP/1.1 Accept: application/json **Response** .. sourcecode:: http HTTP/1.1 200 OK Content-Type: application/json [ { "id": 1, "path_osx": "/mnt/nfs", "path_windows": "\\\\domains\\cifs_server", "path_linux": "/mnt/nfs" }, { "id": 7, "path_osx": "/renderout", "path_windows": "c:\\renderout", "path_linux": "/renderout" "tag": "usual", } ] :statuscode 200: no error

<|skeleton|>
class PathMapIndexAPI:

    def post(self):
        """A ``POST`` to this endpoint will create a new path map. A path map will list the equivalent path prefixes for all three supported families of operating systems, Linux, Windows and OS X. A path map can optionally be restricted to one tag, in which case it will only apply to agents with that tag. If a tag is specified that does not exist yet, that tag will be transparently created. .. http:post:: /api/v1/pathmaps/ HTTP/1.1 **Request** .. sourcecode:: http POST /api/v1/pathmaps/ HTTP/1.1 Accept: application/json { "path_linux": "/mnt/nfs", "path_windows": "\\domain\\cifs_server", "path_osx": "/mnt/nfs", "tag": "production" } **Response** .. sourcecode:: http HTTP/1.1 201 CREATED Content-Type: a"""
        <|body_0|>

    def get(self):
        """A ``GET`` to this endpoint will return a list of all registered path maps, with id. It can be made with a for_agent query parameter, in which case it will return only those path maps that apply to that agent. .. http:get:: /api/v1/pathmaps/ HTTP/1.1 **Request** .. sourcecode:: http GET /api/v1/pathmaps/ HTTP/1.1 Accept: application/json **Response** .. sourcecode:: http HTTP/1.1 200 OK Content-Type: application/json [ { "id": 1, "path_osx": "/mnt/nfs", "path_windows": "\\\\domains\\cifs_server", "path_linux": "/mnt/nfs" }, { "id": 7, "path_osx": "/renderout", "path_windows": "c:\\renderout", "path_linux": "/renderout" "tag": "usual", } ] :statuscode 200: no error"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        tagname = g.json.pop('tag', None)
        if tagname:
            if not isinstance(tagname, STRING_TYPES):
                return (jsonify(error='tag must be of type string'), BAD_REQUEST)
        pathmap = PathMap(**g.json)
        if tagname:
            tag = Tag.query.filter_by(tag=tagname).first()
            if not tag:
                tag = Tag(tag=tagname)
                db.session.add(tag)
            pathmap.tag = tag
        db.session.add(pathmap)
        db.session.commit()
        out = pathmap.to_dict(unpack_relationships=False)
        if pathmap.tag:
            out['tag'] = pathmap.tag.tag
        logger.info('New pathmap created with values: %r', pathmap)
        return (jsonify(out), CREATED)
<|end_body_0|>

<|body_start_1|>
        query = PathMap.query
        for_agent = get_uuid_argument('for_agent')
        if for_agent:
            query = query.filter(or_(PathMap.tag == None, PathMap.tag.has(Tag.agents.any(Agent.id == for_agent))))
        logger.debug('Query: %s', str(query))
        output = []
        for map in query:
            map_dict = map.to_dict(unpack_relationships=False)
            if map.tag:
                map_dict['tag'] = map.tag.tag
            del map_dict['tag_id']
            output.append(map_dict)
        return (jsonify(output), OK)
<|end_body_1|>

Solution:
class PathMapIndexAPI:
    def post(self):
        """A ``POST`` to this endpoint will create a new path map. A path map will list the equivalent path prefixes for all three supported families of operating systems, Linux, Windows and OS X. A path map can optionally be restricted to one tag, in which case it will only apply to agents with that tag. If a tag is specified that does not exist yet, that tag will be transparently created. .. http:post:: /api/v1/pathmaps/ HTTP/1.1 **Request** .. sourcecode:: http POST /api/v1/pathmaps/ HTTP/1.1 Accept: application/json { "path_linux": "/mnt/nfs", "path_windows": "\\domain\\cifs_server", "path_osx": "/mnt/nfs", "tag": "production" } **Response** .. sourcecode:: http HTTP/1.1 201 CREATED Content-Type: a"""
        tagname = g.json.pop('tag', None)
        if tagname:
            if not isinstance(tagname, STRING_TYPES):
                return (jsonify(error='tag must be of type string'), BAD_REQUEST)
        pathmap = PathMap(**g.json)
        if tagname:
            tag = Tag.query.filter_by(tag=tagname).first()
            if not tag:
                tag = Tag(tag=tagname)
                db.session.add(tag)
            pathmap.tag = tag
        db.session.add(pathmap)
        db.session.commit()
        out = pathmap.to_dict(unpack_relationships=False)
        if pathmap.tag:
            out['tag'] = pathmap.tag.tag
        logger.info('New pathmap created with values: %r', pathmap)
        return (jsonify(out), CREATED)

    def get(self):
        """A ``GET`` to this endpoint will return a list of all registered path maps, with id. It can be made with a for_agent query parameter, in which case it will return only those path maps that apply to that agent. .. http:get:: /api/v1/pathmaps/ HTTP/1.1 **Request** .. sourcecode:: http GET /api/v1/pathmaps/ HTTP/1.1 Accept: application/json **Response** .. sourcecode:: http HTTP/1.1 200 OK Content-Type: application/json [ { "id": 1, "path_osx": "/mnt/nfs", "path_windows": "\\\\domains\\cifs_server", "path_linux": "/mnt/nfs" }, { "id": 7, "path_osx": "/renderout", "path_windows": "c:\\renderout", "path_linux": "/renderout" "tag": "usual", } ] :statuscode 200: no error"""
        query = PathMap.query
        for_agent = get_uuid_argument('for_agent')
        if for_agent:
            query = query.filter(or_(PathMap.tag == None, PathMap.tag.has(Tag.agents.any(Agent.id == for_agent))))
        logger.debug('Query: %s', str(query))
        output = []
        for map in query:
            map_dict = map.to_dict(unpack_relationships=False)
            if map.tag:
                map_dict['tag'] = map.tag.tag
            del map_dict['tag_id']
            output.append(map_dict)
        return (jsonify(output), OK)


isInterleave

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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def isInterleave(self, s1: str, s2: str, s3: str) -> bool: dp[i][j] 代表 前i个s1,与前j个s2,是否交错组成前i+j个s3 dp[0][0] = True dp[0][j] dp[j][0] dp[i][j] = dp[i-1_最短回文串.py][j] if s1[i-1_最短回文串.py] == s3[i+j-1_最短回文串.py] = dp[i][j-1_最短回文串.py] if s2[j-1_最短回文串.py] == s3[i+j-1_最短回文串.py] = dp[i-1_最短回文串.py][j] or dp[i][j-1_最短回文串.py] if s2[j-1_最短回文串.py] == s1[i-1_最短回文串.py] == s3[i+j-1_最短回文串.py] res = dp[-1_最短回文串.py][-1_最短回文串.py]
- def isInterleave(self, s1: str, s2: str, s3: str) -> bool: dp[i][j] 代表 前i个s1,与前j个s2,是否交错组成前i+j个s3 dp[0][0] = True dp[0][j] dp[j][0] dp[i][j] = dp[i-1_最短回文串.py][j] if s1[i-1_最短回文串.py] == s3[i+j-1_最短回文串.py] = dp[i][j-1_最短回文串.py] if s2[j-1_最短回文串.py] == s3[i+j-1_最短回文串.py] = dp[i-1_最短回文串.py][j] or dp[i][j-1_最短回文串.py] if s2[j-1_最短回文串.py] == s1[i-1_最短回文串.py] == s3[i+j-1_最短回文串.py] res = dp[-1_最短回文串.py][-1_最短回文串.py]

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def isInterleave(self, s1: str, s2: str, s3: str) -> bool: dp[i][j] 代表 前i个s1,与前j个s2,是否交错组成前i+j个s3 dp[0][0] = True dp[0][j] dp[j][0] dp[i][j] = dp[i-1_最短回文串.py][j] if s1[i-1_最短回文串.py] == s3[i+j-1_最短回文串.py] = dp[i][j-1_最短回文串.py] if s2[j-1_最短回文串.py] == s3[i+j-1_最短回文串.py] = dp[i-1_最短回文串.py][j] or dp[i][j-1_最短回文串.py] if s2[j-1_最短回文串.py] == s1[i-1_最短回文串.py] == s3[i+j-1_最短回文串.py] res = dp[-1_最短回文串.py][-1_最短回文串.py]
- def isInterleave(self, s1: str, s2: str, s3: str) -> bool: dp[i][j] 代表 前i个s1,与前j个s2,是否交错组成前i+j个s3 dp[0][0] = True dp[0][j] dp[j][0] dp[i][j] = dp[i-1_最短回文串.py][j] if s1[i-1_最短回文串.py] == s3[i+j-1_最短回文串.py] = dp[i][j-1_最短回文串.py] if s2[j-1_最短回文串.py] == s3[i+j-1_最短回文串.py] = dp[i-1_最短回文串.py][j] or dp[i][j-1_最短回文串.py] if s2[j-1_最短回文串.py] == s1[i-1_最短回文串.py] == s3[i+j-1_最短回文串.py] res = dp[-1_最短回文串.py][-1_最短回文串.py]

<|skeleton|>
class Solution:

    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        """dp[i][j] 代表 前i个s1,与前j个s2,是否交错组成前i+j个s3 dp[0][0] = True dp[0][j] dp[j][0] dp[i][j] = dp[i-1_最短回文串.py][j] if s1[i-1_最短回文串.py] == s3[i+j-1_最短回文串.py] = dp[i][j-1_最短回文串.py] if s2[j-1_最短回文串.py] == s3[i+j-1_最短回文串.py] = dp[i-1_最短回文串.py][j] or dp[i][j-1_最短回文串.py] if s2[j-1_最短回文串.py] == s1[i-1_最短回文串.py] == s3[i+j-1_最短回文串.py] res = dp[-1_最短回文串.py][-1_最短回文串.py]"""
        <|body_0|>

    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        """dp[i][j] 代表 前i个s1,与前j个s2,是否交错组成前i+j个s3 dp[0][0] = True dp[0][j] dp[j][0] dp[i][j] = dp[i-1_最短回文串.py][j] if s1[i-1_最短回文串.py] == s3[i+j-1_最短回文串.py] = dp[i][j-1_最短回文串.py] if s2[j-1_最短回文串.py] == s3[i+j-1_最短回文串.py] = dp[i-1_最短回文串.py][j] or dp[i][j-1_最短回文串.py] if s2[j-1_最短回文串.py] == s1[i-1_最短回文串.py] == s3[i+j-1_最短回文串.py] res = dp[-1_最短回文串.py][-1_最短回文串.py]"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        m, n, s = (len(s1), len(s2), len(s3))
        if s != m + n:
            return False
        dp = [[False] * (n + 1) for _ in range(m + 1)]
        dp[0][0] = True
        for i in range(1, n + 1):
            if s2[i - 1] == s3[i - 1]:
                dp[0][i] = dp[0][i - 1]
        for i in range(1, m + 1):
            if s1[i - 1] == s3[i - 1]:
                dp[i][0] = dp[i - 1][0]
        for i in range(1, m + 1):
            for j in range(1, n + 1):
                if s1[i - 1] == s2[j - 1] == s3[i + j - 1]:
                    dp[i][j] = dp[i - 1][j] or dp[i][j - 1]
                elif s2[j - 1] == s3[i + j - 1]:
                    dp[i][j] = dp[i][j - 1]
                elif s1[i - 1] == s3[i + j - 1]:
                    dp[i][j] = dp[i - 1][j]
                else:
                    dp[i][j] = False
        return dp[-1][-1]
<|end_body_0|>

<|body_start_1|>
        m, n, s = (len(s1), len(s2), len(s3))
        if s != m + n:
            return False
        dp = [[False] * (n + 1) for _ in range(m + 1)]
        dp[0][0] = True
        for i in range(1, n + 1):
            if s2[i - 1] == s3[i - 1]:
                dp[0][i] = dp[0][i - 1]
        for i in range(1, m + 1):
            if s1[i - 1] == s3[i - 1]:
                dp[i][0] = dp[i - 1][0]
        for i in range(1, m + 1):
            for j in range(1, n + 1):
                if s1[i - 1] == s2[j - 1] == s3[i + j - 1]:
                    dp[i][j] = dp[i - 1][j] or dp[i][j - 1]
                elif s2[j - 1] == s3[i + j - 1]:
                    dp[i][j] = dp[i][j - 1]
                elif s1[i - 1] == s3[i + j - 1]:
                    dp[i][j] = dp[i - 1][j]
                else:
                    dp[i][j] = False
        return dp[-1][-1]
<|end_body_1|>

Solution:
class Solution:
    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        """dp[i][j] 代表 前i个s1,与前j个s2,是否交错组成前i+j个s3 dp[0][0] = True dp[0][j] dp[j][0] dp[i][j] = dp[i-1_最短回文串.py][j] if s1[i-1_最短回文串.py] == s3[i+j-1_最短回文串.py] = dp[i][j-1_最短回文串.py] if s2[j-1_最短回文串.py] == s3[i+j-1_最短回文串.py] = dp[i-1_最短回文串.py][j] or dp[i][j-1_最短回文串.py] if s2[j-1_最短回文串.py] == s1[i-1_最短回文串.py] == s3[i+j-1_最短回文串.py] res = dp[-1_最短回文串.py][-1_最短回文串.py]"""
        m, n, s = (len(s1), len(s2), len(s3))
        if s != m + n:
            return False
        dp = [[False] * (n + 1) for _ in range(m + 1)]
        dp[0][0] = True
        for i in range(1, n + 1):
            if s2[i - 1] == s3[i - 1]:
                dp[0][i] = dp[0][i - 1]
        for i in range(1, m + 1):
            if s1[i - 1] == s3[i - 1]:
                dp[i][0] = dp[i - 1][0]
        for i in range(1, m + 1):
            for j in range(1, n + 1):
                if s1[i - 1] == s2[j - 1] == s3[i + j - 1]:
                    dp[i][j] = dp[i - 1][j] or dp[i][j - 1]
                elif s2[j - 1] == s3[i + j - 1]:
                    dp[i][j] = dp[i][j - 1]
                elif s1[i - 1] == s3[i + j - 1]:
                    dp[i][j] = dp[i - 1][j]
                else:
                    dp[i][j] = False
        return dp[-1][-1]

    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        """dp[i][j] 代表 前i个s1,与前j个s2,是否交错组成前i+j个s3 dp[0][0] = True dp[0][j] dp[j][0] dp[i][j] = dp[i-1_最短回文串.py][j] if s1[i-1_最短回文串.py] == s3[i+j-1_最短回文串.py] = dp[i][j-1_最短回文串.py] if s2[j-1_最短回文串.py] == s3[i+j-1_最短回文串.py] = dp[i-1_最短回文串.py][j] or dp[i][j-1_最短回文串.py] if s2[j-1_最短回文串.py] == s1[i-1_最短回文串.py] == s3[i+j-1_最短回文串.py] res = dp[-1_最短回文串.py][-1_最短回文串.py]"""
        m, n, s = (len(s1), len(s2), len(s3))
        if s != m + n:
            return False
        dp = [[False] * (n + 1) for _ in range(m + 1)]
        dp[0][0] = True
        for i in range(1, n + 1):
            if s2[i - 1] == s3[i - 1]:
                dp[0][i] = dp[0][i - 1]
        for i in range(1, m + 1):
            if s1[i - 1] == s3[i - 1]:
                dp[i][0] = dp[i - 1][0]
        for i in range(1, m + 1):
            for j in range(1, n + 1):
                if s1[i - 1] == s2[j - 1] == s3[i + j - 1]:
                    dp[i][j] = dp[i - 1][j] or dp[i][j - 1]
                elif s2[j - 1] == s3[i + j - 1]:
                    dp[i][j] = dp[i][j - 1]
                elif s1[i - 1] == s3[i + j - 1]:
                    dp[i][j] = dp[i - 1][j]
                else:
                    dp[i][j] = False
        return dp[-1][-1]


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

Class description:
User creation form class.

Method signatures and docstrings:
- def clean_full_name(self): Validate fullname.
- def clean_email2(self): Validate email 2.

Implement the Python class `UserRegisterForm` described below.

Class description:
User creation form class.

Method signatures and docstrings:
- def clean_full_name(self): Validate fullname.
- def clean_email2(self): Validate email 2.

<|skeleton|>
class UserRegisterForm:
    """User creation form class."""

    def clean_full_name(self):
        """Validate fullname."""
        <|body_0|>

    def clean_email2(self):
        """Validate email 2."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        full_name = self.cleaned_data.get('full_name')
        forbidden_users = ['admin', 'user', 'login', 'authenticate', 'css', 'js', 'logout', 'adminstrator', 'root', 'email', 'join', 'sql', 'static', 'python', 'delete']
        if full_name.lower() in forbidden_users:
            raise forms.ValidationError('This is a reserved word.', code='reserved word')
        if '@' in full_name or '-' in full_name or '+' in full_name or ('=' in full_name):
            raise forms.ValidationError('This is an Invalid Name, Do not use these chars: @ , - , + , =', code='invalid')
        return full_name
<|end_body_0|>

<|body_start_1|>
        email1 = self.cleaned_data.get('email')
        email2 = self.cleaned_data.get('email2')
        if email1 != email2:
            raise forms.ValidationError('The two email fields didn’t match.', code="emails don't match")
        if User.objects.filter(email__iexact=email2).exists():
            raise forms.ValidationError('An account with this Email already exists.', code='email exists')
        return email2
<|end_body_1|>

Solution:
class UserRegisterForm:
    """User creation form class."""

    def clean_full_name(self):
        """Validate fullname."""
        full_name = self.cleaned_data.get('full_name')
        forbidden_users = ['admin', 'user', 'login', 'authenticate', 'css', 'js', 'logout', 'adminstrator', 'root', 'email', 'join', 'sql', 'static', 'python', 'delete']
        if full_name.lower() in forbidden_users:
            raise forms.ValidationError('This is a reserved word.', code='reserved word')
        if '@' in full_name or '-' in full_name or '+' in full_name or ('=' in full_name):
            raise forms.ValidationError('This is an Invalid Name, Do not use these chars: @ , - , + , =', code='invalid')
        return full_name

    def clean_email2(self):
        """Validate email 2."""
        email1 = self.cleaned_data.get('email')
        email2 = self.cleaned_data.get('email2')
        if email1 != email2:
            raise forms.ValidationError('The two email fields didn’t match.', code="emails don't match")
        if User.objects.filter(email__iexact=email2).exists():
            raise forms.ValidationError('An account with this Email already exists.', code='email exists')
        return email2