getNextPrime

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

Class description:
Implement the PrimeGen class.

Method signatures and docstrings:
- def sieve_of_e(self, max_num): Generating a List of Primes: The Sieve of Eratosthenes * All nonprime nums are divisible by a prime number * Alg: - Start w/ list of all numbers up to max - Cross off alt numbers divisible by 2, by 3, ... - This gives us a list of all primes # >>> pg = PrimeGen() # >>> pg.sieve_of_e(13)
- def isPrime(self, n): Return bool for primality of `n` >>> pg = PrimeGen() >>> pg.isPrime(13) True >>> pg.isPrime(2) True >>> pg.isPrime(14) False
- def getNextPrime(self, p): Return the smallest prime number greater than prime `p` >>> pg = PrimeGen() >>> pg.getNextPrime(0) 2 >>> pg.getNextPrime(2) 3 >>> pg.getNextPrime(6) 7 >>> pg.getNextPrime(16) 17

Implement the Python class `PrimeGen` described below.

Class description:
Implement the PrimeGen class.

Method signatures and docstrings:
- def sieve_of_e(self, max_num): Generating a List of Primes: The Sieve of Eratosthenes * All nonprime nums are divisible by a prime number * Alg: - Start w/ list of all numbers up to max - Cross off alt numbers divisible by 2, by 3, ... - This gives us a list of all primes # >>> pg = PrimeGen() # >>> pg.sieve_of_e(13)
- def isPrime(self, n): Return bool for primality of `n` >>> pg = PrimeGen() >>> pg.isPrime(13) True >>> pg.isPrime(2) True >>> pg.isPrime(14) False
- def getNextPrime(self, p): Return the smallest prime number greater than prime `p` >>> pg = PrimeGen() >>> pg.getNextPrime(0) 2 >>> pg.getNextPrime(2) 3 >>> pg.getNextPrime(6) 7 >>> pg.getNextPrime(16) 17

<|skeleton|>
class PrimeGen:

    def sieve_of_e(self, max_num):
        """Generating a List of Primes: The Sieve of Eratosthenes * All nonprime nums are divisible by a prime number * Alg: - Start w/ list of all numbers up to max - Cross off alt numbers divisible by 2, by 3, ... - This gives us a list of all primes # >>> pg = PrimeGen() # >>> pg.sieve_of_e(13)"""
        <|body_0|>

    def isPrime(self, n):
        """Return bool for primality of `n` >>> pg = PrimeGen() >>> pg.isPrime(13) True >>> pg.isPrime(2) True >>> pg.isPrime(14) False"""
        <|body_1|>

    def getNextPrime(self, p):
        """Return the smallest prime number greater than prime `p` >>> pg = PrimeGen() >>> pg.getNextPrime(0) 2 >>> pg.getNextPrime(2) 3 >>> pg.getNextPrime(6) 7 >>> pg.getNextPrime(16) 17"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        flags = [0, 1] + [True] * (max_num + 1)
        count = 0
        prime = 2
        while prime <= math.sqrt(max_num):
            for i in range(prime * prime, len(flags), prime):
                flags[i] = False
            break
        return flags
<|end_body_0|>

<|body_start_1|>
        if n <= 1:
            return False
        for x in range(2, n):
            if n % x == 0:
                return False
        return True
<|end_body_1|>

<|body_start_2|>
        if p <= 1:
            return 2
        prime = p
        found = False
        while True:
            prime += 1
            if self.isPrime(prime):
                return prime
        return prime
<|end_body_2|>

Solution:
class PrimeGen:
    def sieve_of_e(self, max_num):
        """Generating a List of Primes: The Sieve of Eratosthenes * All nonprime nums are divisible by a prime number * Alg: - Start w/ list of all numbers up to max - Cross off alt numbers divisible by 2, by 3, ... - This gives us a list of all primes # >>> pg = PrimeGen() # >>> pg.sieve_of_e(13)"""
        flags = [0, 1] + [True] * (max_num + 1)
        count = 0
        prime = 2
        while prime <= math.sqrt(max_num):
            for i in range(prime * prime, len(flags), prime):
                flags[i] = False
            break
        return flags

    def isPrime(self, n):
        """Return bool for primality of `n` >>> pg = PrimeGen() >>> pg.isPrime(13) True >>> pg.isPrime(2) True >>> pg.isPrime(14) False"""
        if n <= 1:
            return False
        for x in range(2, n):
            if n % x == 0:
                return False
        return True

    def getNextPrime(self, p):
        """Return the smallest prime number greater than prime `p` >>> pg = PrimeGen() >>> pg.getNextPrime(0) 2 >>> pg.getNextPrime(2) 3 >>> pg.getNextPrime(6) 7 >>> pg.getNextPrime(16) 17"""
        if p <= 1:
            return 2
        prime = p
        found = False
        while True:
            prime += 1
            if self.isPrime(prime):
                return prime
        return prime


clear

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

Class description:
Set to manager Priority Addons used in Warmup

Method signatures and docstrings:
- def add(self, addon): Overriding method that also adds all addons to PriorityAddon
- def clear(self): Overriding method that also removes addons from PriorityAddon

Implement the Python class `Priorities` described below.

Class description:
Set to manager Priority Addons used in Warmup

Method signatures and docstrings:
- def add(self, addon): Overriding method that also adds all addons to PriorityAddon
- def clear(self): Overriding method that also removes addons from PriorityAddon

<|skeleton|>
class Priorities:
    """Set to manager Priority Addons used in Warmup"""

    def add(self, addon):
        """Overriding method that also adds all addons to PriorityAddon"""
        <|body_0|>

    def clear(self):
        """Overriding method that also removes addons from PriorityAddon"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        if not addon in PriorityAddon:
            PriorityAddon.add(addon)
            super(Priorities, self).add(addon)
<|end_body_0|>

<|body_start_1|>
        for addon in self:
            PriorityAddon.discard(addon)
        super(Priorities, self).clear()
<|end_body_1|>

Solution:
class Priorities:
    """Set to manager Priority Addons used in Warmup"""

    def add(self, addon):
        """Overriding method that also adds all addons to PriorityAddon"""
        if not addon in PriorityAddon:
            PriorityAddon.add(addon)
            super(Priorities, self).add(addon)

    def clear(self):
        """Overriding method that also removes addons from PriorityAddon"""
        for addon in self:
            PriorityAddon.discard(addon)
        super(Priorities, self).clear()


checkInclusion

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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def checkInclusion(self, s1: str, s2: str) -> bool: CREATED AT: 2022/2/11 Runtime: 92 ms, faster than 68.01% Memory Usage: 14 MB, less than 83.82% 1 <= s1.length, s2.length <= 10^4 s1 and s2 consist of lowercase English letters. :param s1: :param s2: :return:
- def checkInclusion2(self, s1: str, s2: str) -> bool: CREATED AT: 2022/2/11 Runtime: 48 ms, faster than 99.79% Memory Usage: 14 MB, less than 93.32% 1 <= s1.length, s2.length <= 10^4 s1 and s2 consist of lowercase English letters. :param s1: :param s2: :return:

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def checkInclusion(self, s1: str, s2: str) -> bool: CREATED AT: 2022/2/11 Runtime: 92 ms, faster than 68.01% Memory Usage: 14 MB, less than 83.82% 1 <= s1.length, s2.length <= 10^4 s1 and s2 consist of lowercase English letters. :param s1: :param s2: :return:
- def checkInclusion2(self, s1: str, s2: str) -> bool: CREATED AT: 2022/2/11 Runtime: 48 ms, faster than 99.79% Memory Usage: 14 MB, less than 93.32% 1 <= s1.length, s2.length <= 10^4 s1 and s2 consist of lowercase English letters. :param s1: :param s2: :return:

<|skeleton|>
class Solution:

    def checkInclusion(self, s1: str, s2: str) -> bool:
        """CREATED AT: 2022/2/11 Runtime: 92 ms, faster than 68.01% Memory Usage: 14 MB, less than 83.82% 1 <= s1.length, s2.length <= 10^4 s1 and s2 consist of lowercase English letters. :param s1: :param s2: :return:"""
        <|body_0|>

    def checkInclusion2(self, s1: str, s2: str) -> bool:
        """CREATED AT: 2022/2/11 Runtime: 48 ms, faster than 99.79% Memory Usage: 14 MB, less than 93.32% 1 <= s1.length, s2.length <= 10^4 s1 and s2 consist of lowercase English letters. :param s1: :param s2: :return:"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        m, n = (len(s1), len(s2))
        if n < m:
            return False
        l1 = [0] * 26
        for c in s1:
            l1[ord(c) - ord('a')] += 1
        for c in s2[:m]:
            l1[ord(c) - ord('a')] -= 1
        if not any(l1):
            return True
        i = 0
        for c in s2[m:]:
            l1[ord(c) - ord('a')] -= 1
            l1[ord(s2[i]) - ord('a')] += 1
            if not any(l1):
                return True
            i += 1
        return False
<|end_body_0|>

<|body_start_1|>
        m, n = (len(s1), len(s2))
        if n < m:
            return False
        l1 = [0] * 26
        for c in s1:
            l1[ord(c) - ord('a')] += 1
        l2 = [0] * 26
        for c in s2[:m]:
            l2[ord(c) - ord('a')] += 1
        if l1 == l2:
            return True
        i = 0
        for c in s2[m:]:
            l2[ord(c) - ord('a')] += 1
            l2[ord(s2[i]) - ord('a')] -= 1
            if l1 == l2:
                return True
            i += 1
        return False
<|end_body_1|>

Solution:
class Solution:
    def checkInclusion(self, s1: str, s2: str) -> bool:
        """CREATED AT: 2022/2/11 Runtime: 92 ms, faster than 68.01% Memory Usage: 14 MB, less than 83.82% 1 <= s1.length, s2.length <= 10^4 s1 and s2 consist of lowercase English letters. :param s1: :param s2: :return:"""
        m, n = (len(s1), len(s2))
        if n < m:
            return False
        l1 = [0] * 26
        for c in s1:
            l1[ord(c) - ord('a')] += 1
        for c in s2[:m]:
            l1[ord(c) - ord('a')] -= 1
        if not any(l1):
            return True
        i = 0
        for c in s2[m:]:
            l1[ord(c) - ord('a')] -= 1
            l1[ord(s2[i]) - ord('a')] += 1
            if not any(l1):
                return True
            i += 1
        return False

    def checkInclusion2(self, s1: str, s2: str) -> bool:
        """CREATED AT: 2022/2/11 Runtime: 48 ms, faster than 99.79% Memory Usage: 14 MB, less than 93.32% 1 <= s1.length, s2.length <= 10^4 s1 and s2 consist of lowercase English letters. :param s1: :param s2: :return:"""
        m, n = (len(s1), len(s2))
        if n < m:
            return False
        l1 = [0] * 26
        for c in s1:
            l1[ord(c) - ord('a')] += 1
        l2 = [0] * 26
        for c in s2[:m]:
            l2[ord(c) - ord('a')] += 1
        if l1 == l2:
            return True
        i = 0
        for c in s2[m:]:
            l2[ord(c) - ord('a')] += 1
            l2[ord(s2[i]) - ord('a')] -= 1
            if l1 == l2:
                return True
            i += 1
        return False


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

Class description:
The NLU model predicted the wrong user utterance. Mostly used to mark wrong predictions and be able to dump them as stories.

Method signatures and docstrings:
- def __init__(self, event: UserUttered, eval_store: EvaluationStore) -> None: Set `predicted_intent` and `predicted_entities` attributes.
- def inline_comment(self, force_comment_generation: bool=False) -> Optional[Text]: A comment attached to this event. Used during dumping.
- def inline_comment_for_entity(predicted: Dict[Text, Any], entity: Dict[Text, Any]) -> Optional[Text]: Returns the predicted entity which is then printed as a comment.
- def as_story_string(self, e2e: bool=True) -> Text: Returns text representation of event.

Implement the Python class `WronglyClassifiedUserUtterance` described below.

Class description:
The NLU model predicted the wrong user utterance. Mostly used to mark wrong predictions and be able to dump them as stories.

Method signatures and docstrings:
- def __init__(self, event: UserUttered, eval_store: EvaluationStore) -> None: Set `predicted_intent` and `predicted_entities` attributes.
- def inline_comment(self, force_comment_generation: bool=False) -> Optional[Text]: A comment attached to this event. Used during dumping.
- def inline_comment_for_entity(predicted: Dict[Text, Any], entity: Dict[Text, Any]) -> Optional[Text]: Returns the predicted entity which is then printed as a comment.
- def as_story_string(self, e2e: bool=True) -> Text: Returns text representation of event.

<|skeleton|>
class WronglyClassifiedUserUtterance:
    """The NLU model predicted the wrong user utterance. Mostly used to mark wrong predictions and be able to dump them as stories."""

    def __init__(self, event: UserUttered, eval_store: EvaluationStore) -> None:
        """Set `predicted_intent` and `predicted_entities` attributes."""
        <|body_0|>

    def inline_comment(self, force_comment_generation: bool=False) -> Optional[Text]:
        """A comment attached to this event. Used during dumping."""
        <|body_1|>

    def inline_comment_for_entity(predicted: Dict[Text, Any], entity: Dict[Text, Any]) -> Optional[Text]:
        """Returns the predicted entity which is then printed as a comment."""
        <|body_2|>

    def as_story_string(self, e2e: bool=True) -> Text:
        """Returns text representation of event."""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        try:
            self.predicted_intent = eval_store.intent_predictions[0]
        except LookupError:
            self.predicted_intent = None
        self.target_entities = eval_store.entity_targets
        self.predicted_entities = eval_store.entity_predictions
        intent = {'name': eval_store.intent_targets[0]}
        super().__init__(event.text, intent, eval_store.entity_targets, event.parse_data, event.timestamp, event.input_channel)
<|end_body_0|>

<|body_start_1|>
        from rasa.shared.core.events import format_message
        if force_comment_generation or self.predicted_intent != self.intent['name']:
            predicted_message = format_message(self.text, self.predicted_intent, self.predicted_entities)
            return f'predicted: {self.predicted_intent}: {predicted_message}'
        else:
            return None
<|end_body_1|>

<|body_start_2|>
        if predicted['entity'] != entity['entity']:
            return 'predicted: ' + predicted['entity'] + ': ' + predicted['value']
        else:
            return None
<|end_body_2|>

<|body_start_3|>
        from rasa.shared.core.events import format_message
        correct_message = format_message(self.text, self.intent.get('name'), self.entities)
        return f"{self.intent.get('name')}: {correct_message}   <!-- {self.inline_comment()} -->"
<|end_body_3|>

Solution:
class WronglyClassifiedUserUtterance:
    """The NLU model predicted the wrong user utterance. Mostly used to mark wrong predictions and be able to dump them as stories."""

    def __init__(self, event: UserUttered, eval_store: EvaluationStore) -> None:
        """Set `predicted_intent` and `predicted_entities` attributes."""
        try:
            self.predicted_intent = eval_store.intent_predictions[0]
        except LookupError:
            self.predicted_intent = None
        self.target_entities = eval_store.entity_targets
        self.predicted_entities = eval_store.entity_predictions
        intent = {'name': eval_store.intent_targets[0]}
        super().__init__(event.text, intent, eval_store.entity_targets, event.parse_data, event.timestamp, event.input_channel)

    def inline_comment(self, force_comment_generation: bool=False) -> Optional[Text]:
        """A comment attached to this event. Used during dumping."""
        from rasa.shared.core.events import format_message
        if force_comment_generation or self.predicted_intent != self.intent['name']:
            predicted_message = format_message(self.text, self.predicted_intent, self.predicted_entities)
            return f'predicted: {self.predicted_intent}: {predicted_message}'
        else:
            return None

    def inline_comment_for_entity(predicted: Dict[Text, Any], entity: Dict[Text, Any]) -> Optional[Text]:
        """Returns the predicted entity which is then printed as a comment."""
        if predicted['entity'] != entity['entity']:
            return 'predicted: ' + predicted['entity'] + ': ' + predicted['value']
        else:
            return None

    def as_story_string(self, e2e: bool=True) -> Text:
        """Returns text representation of event."""
        from rasa.shared.core.events import format_message
        correct_message = format_message(self.text, self.intent.get('name'), self.entities)
        return f"{self.intent.get('name')}: {correct_message}   <!-- {self.inline_comment()} -->"


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

Class description:
A class to perform empirical masking

Method signatures and docstrings:
- def __init__(self, experiment, reference): Initialise the masking algorithms Params: experiment The experiment data
- def __call__(self, reflections, adjacency_list=None): Mask the given reflections. Params: reflections The reflection list adjacency_list The adjacency_list (optional) Returns: The masked reflection list

Implement the Python class `MaskerEmpirical` described below.

Class description:
A class to perform empirical masking

Method signatures and docstrings:
- def __init__(self, experiment, reference): Initialise the masking algorithms Params: experiment The experiment data
- def __call__(self, reflections, adjacency_list=None): Mask the given reflections. Params: reflections The reflection list adjacency_list The adjacency_list (optional) Returns: The masked reflection list

<|skeleton|>
class MaskerEmpirical:
    """A class to perform empirical masking"""

    def __init__(self, experiment, reference):
        """Initialise the masking algorithms Params: experiment The experiment data"""
        <|body_0|>

    def __call__(self, reflections, adjacency_list=None):
        """Mask the given reflections. Params: reflections The reflection list adjacency_list The adjacency_list (optional) Returns: The masked reflection list"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        super().__init__(experiment)
        from dials.algorithms.shoebox import MaskEmpirical
        self.mask_empirical = MaskEmpirical(reference)
        self._reference = reference
<|end_body_0|>

<|body_start_1|>
        reflections = super().__call__(reflections, adjacency_list)
        if self.mask_empirical:
            self.mask_empirical(reflections)
        return reflections
<|end_body_1|>

Solution:
class MaskerEmpirical:
    """A class to perform empirical masking"""

    def __init__(self, experiment, reference):
        """Initialise the masking algorithms Params: experiment The experiment data"""
        super().__init__(experiment)
        from dials.algorithms.shoebox import MaskEmpirical
        self.mask_empirical = MaskEmpirical(reference)
        self._reference = reference

    def __call__(self, reflections, adjacency_list=None):
        """Mask the given reflections. Params: reflections The reflection list adjacency_list The adjacency_list (optional) Returns: The masked reflection list"""
        reflections = super().__call__(reflections, adjacency_list)
        if self.mask_empirical:
            self.mask_empirical(reflections)
        return reflections


patch

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

Class description:
Implement the BiographyView class.

Method signatures and docstrings:
- def index(self): Return the newest Biography entry.
- def post(self): Add a new Biography entry.
- def put(self): Overwrite the newest Biography with a new one.
- def patch(self): Update the newest Biography entry partially.

Implement the Python class `BiographyView` described below.

Class description:
Implement the BiographyView class.

Method signatures and docstrings:
- def index(self): Return the newest Biography entry.
- def post(self): Add a new Biography entry.
- def put(self): Overwrite the newest Biography with a new one.
- def patch(self): Update the newest Biography entry partially.

<|skeleton|>
class BiographyView:

    def index(self):
        """Return the newest Biography entry."""
        <|body_0|>

    def post(self):
        """Add a new Biography entry."""
        <|body_1|>

    def put(self):
        """Overwrite the newest Biography with a new one."""
        <|body_2|>

    def patch(self):
        """Update the newest Biography entry partially."""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        newest = Biography.query.order_by(desc(Biography.BiographyID)).first_or_404()
        content = jsonify({'biography': [{'short': newest.Short, 'full': newest.Full, 'createdAt': newest.Created, 'updatedAt': newest.Updated}]})
        return make_response(content, 200)
<|end_body_0|>

<|body_start_1|>
        data = json.loads(request.data.decode())
        bio = Biography(Short=data['short'], Full=data['full'], Created=get_datetime())
        db.session.add(bio)
        db.session.commit()
        server = socket.gethostname()
        contents = 'Location: {}{}{}'.format(server, url_for('BiographyView:index'), bio.BiographyID)
        return make_response(jsonify(contents), 201)
<|end_body_1|>

<|body_start_2|>
        data = json.loads(request.data.decode())
        bio = Biography.query.order_by(desc(Biography.BiographyID)).first_or_404()
        bio.Short = data['short']
        bio.Full = data['full']
        bio.Updated = get_datetime()
        db.session.commit()
        return make_response('', 200)
<|end_body_2|>

<|body_start_3|>
        bio = Biography.query.order_by(desc(Biography.BiographyID)).first_or_404()
        result = []
        status_code = 204
        try:
            result = patch_item(bio, request.get_json())
            db.session.commit()
        except Exception:
            result = {'success': False, 'error': 'Could not apply patch'}
            status_code = 422
        return make_response(jsonify(result), status_code)
<|end_body_3|>

Solution:
class BiographyView:
    def index(self):
        """Return the newest Biography entry."""
        newest = Biography.query.order_by(desc(Biography.BiographyID)).first_or_404()
        content = jsonify({'biography': [{'short': newest.Short, 'full': newest.Full, 'createdAt': newest.Created, 'updatedAt': newest.Updated}]})
        return make_response(content, 200)

    def post(self):
        """Add a new Biography entry."""
        data = json.loads(request.data.decode())
        bio = Biography(Short=data['short'], Full=data['full'], Created=get_datetime())
        db.session.add(bio)
        db.session.commit()
        server = socket.gethostname()
        contents = 'Location: {}{}{}'.format(server, url_for('BiographyView:index'), bio.BiographyID)
        return make_response(jsonify(contents), 201)

    def put(self):
        """Overwrite the newest Biography with a new one."""
        data = json.loads(request.data.decode())
        bio = Biography.query.order_by(desc(Biography.BiographyID)).first_or_404()
        bio.Short = data['short']
        bio.Full = data['full']
        bio.Updated = get_datetime()
        db.session.commit()
        return make_response('', 200)

    def patch(self):
        """Update the newest Biography entry partially."""
        bio = Biography.query.order_by(desc(Biography.BiographyID)).first_or_404()
        result = []
        status_code = 204
        try:
            result = patch_item(bio, request.get_json())
            db.session.commit()
        except Exception:
            result = {'success': False, 'error': 'Could not apply patch'}
            status_code = 422
        return make_response(jsonify(result), status_code)


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

Class description:
A widget containing a list of files and/or directories.

Method signatures and docstrings:
- def __init__(self, image_display_figure): Point the filelist widget to a default directory and fill it with the contents of that directory. Hook up a mouse double-click to call the 'item_click' method.
- def add_items(self): Add items from the 'current_directory' to the list.
- def item_click(self, item): The user clicked on an item, decide what to do based on the item.
- def set_current_directory(self, new_dir): Set the current directory to 'new_dir' and then reload the list.

Implement the Python class `FileList` described below.

Class description:
A widget containing a list of files and/or directories.

Method signatures and docstrings:
- def __init__(self, image_display_figure): Point the filelist widget to a default directory and fill it with the contents of that directory. Hook up a mouse double-click to call the 'item_click' method.
- def add_items(self): Add items from the 'current_directory' to the list.
- def item_click(self, item): The user clicked on an item, decide what to do based on the item.
- def set_current_directory(self, new_dir): Set the current directory to 'new_dir' and then reload the list.

<|skeleton|>
class FileList:
    """A widget containing a list of files and/or directories."""

    def __init__(self, image_display_figure):
        """Point the filelist widget to a default directory and fill it with the contents of that directory. Hook up a mouse double-click to call the 'item_click' method."""
        <|body_0|>

    def add_items(self):
        """Add items from the 'current_directory' to the list."""
        <|body_1|>

    def item_click(self, item):
        """The user clicked on an item, decide what to do based on the item."""
        <|body_2|>

    def set_current_directory(self, new_dir):
        """Set the current directory to 'new_dir' and then reload the list."""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        QListWidget.__init__(self)
        self.current_directory = '/data/lemi-archive-2016-04/*'
        self.add_items()
        self.image_display_figure = image_display_figure
        self.itemDoubleClicked.connect(self.item_click)
<|end_body_0|>

<|body_start_1|>
        item_text = '..'
        item = QListWidgetItem(item_text)
        self.addItem(item)
        file_list = glob.glob(self.current_directory)
        for item_text in file_list:
            if os.path.isfile(item_text) and (item_text.endswith('fits') or item_text.endswith('fit')):
                try:
                    naxis1 = fits.getval(item_text, 'NAXIS1')
                    naxis2 = fits.getval(item_text, 'NAXIS2')
                    objname = fits.getval(item_text, 'OBJNAME')
                    observer = fits.getval(item_text, 'OBSERVER')
                    exptime = fits.getval(item_text, 'EXPTIME')
                    try:
                        filters = fits.getval(item_text, 'FILTERS')
                    except:
                        filters = 'not defined'
                    item_text = item_text + ' (' + str(naxis1) + ',' + str(naxis2) + ') ' + objname + '  ' + observer + '  ' + str(exptime) + '  ' + str(filters)
                    item = QListWidgetItem(item_text)
                    self.addItem(item)
                except Exception as e:
                    print(str(e))
                    print(item_text)
                    print('error accessing FITS file or not a FITS file')
            else:
                item_text = item_text + '/'
                item = QListWidgetItem(item_text)
                self.addItem(item)
<|end_body_1|>

<|body_start_2|>
        dir_file = str(item.text())
        dir_file = dir_file.split()[0]
        if str(dir_file) == '..':
            if self.current_directory.endswith('*'):
                if os.path.dirname(self.current_directory[:-2]) != '/':
                    new_dir = os.path.dirname(self.current_directory[:-2]) + '/*'
                else:
                    new_dir = os.path.dirname(self.current_directory[:-2]) + '*'
            else:
                new_dir = os.path.dirname(self.current_directory) + '*'
            self.set_current_directory(new_dir)
        elif os.path.isfile(str(dir_file)):
            self.image_display_figure.update_image(dir_file)
        else:
            self.set_current_directory(dir_file + '*')
<|end_body_2|>

<|body_start_3|>
        self.current_directory = new_dir
        self.clear()
        self.add_items()
        self.update()
<|end_body_3|>

Solution:
class FileList:
    """A widget containing a list of files and/or directories."""

    def __init__(self, image_display_figure):
        """Point the filelist widget to a default directory and fill it with the contents of that directory. Hook up a mouse double-click to call the 'item_click' method."""
        QListWidget.__init__(self)
        self.current_directory = '/data/lemi-archive-2016-04/*'
        self.add_items()
        self.image_display_figure = image_display_figure
        self.itemDoubleClicked.connect(self.item_click)

    def add_items(self):
        """Add items from the 'current_directory' to the list."""
        item_text = '..'
        item = QListWidgetItem(item_text)
        self.addItem(item)
        file_list = glob.glob(self.current_directory)
        for item_text in file_list:
            if os.path.isfile(item_text) and (item_text.endswith('fits') or item_text.endswith('fit')):
                try:
                    naxis1 = fits.getval(item_text, 'NAXIS1')
                    naxis2 = fits.getval(item_text, 'NAXIS2')
                    objname = fits.getval(item_text, 'OBJNAME')
                    observer = fits.getval(item_text, 'OBSERVER')
                    exptime = fits.getval(item_text, 'EXPTIME')
                    try:
                        filters = fits.getval(item_text, 'FILTERS')
                    except:
                        filters = 'not defined'
                    item_text = item_text + ' (' + str(naxis1) + ',' + str(naxis2) + ') ' + objname + '  ' + observer + '  ' + str(exptime) + '  ' + str(filters)
                    item = QListWidgetItem(item_text)
                    self.addItem(item)
                except Exception as e:
                    print(str(e))
                    print(item_text)
                    print('error accessing FITS file or not a FITS file')
            else:
                item_text = item_text + '/'
                item = QListWidgetItem(item_text)
                self.addItem(item)

    def item_click(self, item):
        """The user clicked on an item, decide what to do based on the item."""
        dir_file = str(item.text())
        dir_file = dir_file.split()[0]
        if str(dir_file) == '..':
            if self.current_directory.endswith('*'):
                if os.path.dirname(self.current_directory[:-2]) != '/':
                    new_dir = os.path.dirname(self.current_directory[:-2]) + '/*'
                else:
                    new_dir = os.path.dirname(self.current_directory[:-2]) + '*'
            else:
                new_dir = os.path.dirname(self.current_directory) + '*'
            self.set_current_directory(new_dir)
        elif os.path.isfile(str(dir_file)):
            self.image_display_figure.update_image(dir_file)
        else:
            self.set_current_directory(dir_file + '*')

    def set_current_directory(self, new_dir):
        """Set the current directory to 'new_dir' and then reload the list."""
        self.current_directory = new_dir
        self.clear()
        self.add_items()
        self.update()


delete

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

Class description:
API Restful methods for Users

Method signatures and docstrings:
- def get(self): GET method Gets an account by id or google token Param: string id or google token Return: dict (account ok / message)
- def post(self): POST method Adds a new account Return: dict (account created / message)
- def put(self, user_id): PUT method Modifies a user Param: id Return: dict (user created)
- def delete(self, user_id): DELETE method Removes an account Param: string id Return: dict (message ok / message)

Implement the Python class `Users` described below.

Class description:
API Restful methods for Users

Method signatures and docstrings:
- def get(self): GET method Gets an account by id or google token Param: string id or google token Return: dict (account ok / message)
- def post(self): POST method Adds a new account Return: dict (account created / message)
- def put(self, user_id): PUT method Modifies a user Param: id Return: dict (user created)
- def delete(self, user_id): DELETE method Removes an account Param: string id Return: dict (message ok / message)

<|skeleton|>
class Users:
    """API Restful methods for Users"""

    def get(self):
        """GET method Gets an account by id or google token Param: string id or google token Return: dict (account ok / message)"""
        <|body_0|>

    def post(self):
        """POST method Adds a new account Return: dict (account created / message)"""
        <|body_1|>

    def put(self, user_id):
        """PUT method Modifies a user Param: id Return: dict (user created)"""
        <|body_2|>

    def delete(self, user_id):
        """DELETE method Removes an account Param: string id Return: dict (message ok / message)"""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        data = parser.parse_args()
        arguments = sum([1 if value else 0 for value in data.values()])
        if arguments > 1:
            return ({'message': 'Please filter by only one feature'}, 400)
        if arguments <= 0:
            return ({'message': 'Please filter by at least one feature: id or google_token'}, 400)
        if data['id']:
            user = UsersModel.find_by_id(user_id=data['id'])
            search_by = ('id', data['id'])
        elif data['google_token']:
            user = UsersModel.find_by_google_token(google_token=data['google_token'])
            search_by = ('Google token', data['google_token'])
        else:
            return ({'message': 'Please filter by a valid feature: id or google_token'}, 400)
        if user:
            return ({'user': user.json()}, 200)
        else:
            return ({'message': 'User with {} [{}] Not found'.format(search_by[0], search_by[1])}, 404)
<|end_body_0|>

<|body_start_1|>
        data = parser.parse_args()
        if not data['mail']:
            return ({'message': {'mail': 'Mail cant be empty'}}, 400)
        if not data['google_token']:
            return ({'message': {'google_token': 'Google token cant be empty'}}, 400)
        if not data['role']:
            return ({'message': {'role': 'Role cant be empty'}}, 400)
        if UsersModel.find_by_mail(data['mail']):
            return ({'message': 'Account with mail [{}] already exists'.format(data['mail'])}, 409)
        user = UsersModel(google_token=data['google_token'], mail=data['mail'], role=data['role'])
        if data['role'] != '0':
            try:
                user.save_to_db()
                return ({'user': UsersModel.find_by_mail(user.mail).json()}, 201)
            except:
                return ({'message': 'Error Description'}, 500)
        else:
            try:
                user.save_to_db()
                return ({'user': UsersModel.find_by_mail(user.mail).json()}, 201)
            except:
                return ({'message': 'Error Description'}, 500)
<|end_body_1|>

<|body_start_2|>
        data = parser.parse_args()
        user = UsersModel.find_by_id(user_id=user_id)
        if data['name']:
            user.name = data['name']
        if data['surname']:
            user.surname = data['surname']
        if data['national_id_document']:
            user.national_id_document = data['national_id_document']
        if data['country']:
            user.country = data['country']
        if data['mail']:
            user.mail = data['mail']
        if data['google_token']:
            user.google_token = data['google_token']
        if data['role']:
            user.role = data['role']
        if data['id_bank_data']:
            user.id_bank_data = data['id_bank_data']
        try:
            user.save_to_db()
            return ({'user': UsersModel.find_by_id(user_id).json()}, 200)
        except:
            return ({'message': 'Error Description'}, 500)
<|end_body_2|>

<|body_start_3|>
        data = parser.parse_args()
        user = UsersModel.find_by_id(user_id=user_id)
        if user:
            try:
                user.delete_from_db()
                return ({'message': 'User with id [{}] and all associated info deleted'.format(user_id)}, 200)
            except:
                return ({'message': 'Error Description'}, 500)
        else:
            return ({'message': 'User with id [{}] Not found'.format(user_id)}, 404)
<|end_body_3|>

Solution:
class Users:
    """API Restful methods for Users"""

    def get(self):
        """GET method Gets an account by id or google token Param: string id or google token Return: dict (account ok / message)"""
        data = parser.parse_args()
        arguments = sum([1 if value else 0 for value in data.values()])
        if arguments > 1:
            return ({'message': 'Please filter by only one feature'}, 400)
        if arguments <= 0:
            return ({'message': 'Please filter by at least one feature: id or google_token'}, 400)
        if data['id']:
            user = UsersModel.find_by_id(user_id=data['id'])
            search_by = ('id', data['id'])
        elif data['google_token']:
            user = UsersModel.find_by_google_token(google_token=data['google_token'])
            search_by = ('Google token', data['google_token'])
        else:
            return ({'message': 'Please filter by a valid feature: id or google_token'}, 400)
        if user:
            return ({'user': user.json()}, 200)
        else:
            return ({'message': 'User with {} [{}] Not found'.format(search_by[0], search_by[1])}, 404)

    def post(self):
        """POST method Adds a new account Return: dict (account created / message)"""
        data = parser.parse_args()
        if not data['mail']:
            return ({'message': {'mail': 'Mail cant be empty'}}, 400)
        if not data['google_token']:
            return ({'message': {'google_token': 'Google token cant be empty'}}, 400)
        if not data['role']:
            return ({'message': {'role': 'Role cant be empty'}}, 400)
        if UsersModel.find_by_mail(data['mail']):
            return ({'message': 'Account with mail [{}] already exists'.format(data['mail'])}, 409)
        user = UsersModel(google_token=data['google_token'], mail=data['mail'], role=data['role'])
        if data['role'] != '0':
            try:
                user.save_to_db()
                return ({'user': UsersModel.find_by_mail(user.mail).json()}, 201)
            except:
                return ({'message': 'Error Description'}, 500)
        else:
            try:
                user.save_to_db()
                return ({'user': UsersModel.find_by_mail(user.mail).json()}, 201)
            except:
                return ({'message': 'Error Description'}, 500)

    def put(self, user_id):
        """PUT method Modifies a user Param: id Return: dict (user created)"""
        data = parser.parse_args()
        user = UsersModel.find_by_id(user_id=user_id)
        if data['name']:
            user.name = data['name']
        if data['surname']:
            user.surname = data['surname']
        if data['national_id_document']:
            user.national_id_document = data['national_id_document']
        if data['country']:
            user.country = data['country']
        if data['mail']:
            user.mail = data['mail']
        if data['google_token']:
            user.google_token = data['google_token']
        if data['role']:
            user.role = data['role']
        if data['id_bank_data']:
            user.id_bank_data = data['id_bank_data']
        try:
            user.save_to_db()
            return ({'user': UsersModel.find_by_id(user_id).json()}, 200)
        except:
            return ({'message': 'Error Description'}, 500)

    def delete(self, user_id):
        """DELETE method Removes an account Param: string id Return: dict (message ok / message)"""
        data = parser.parse_args()
        user = UsersModel.find_by_id(user_id=user_id)
        if user:
            try:
                user.delete_from_db()
                return ({'message': 'User with id [{}] and all associated info deleted'.format(user_id)}, 200)
            except:
                return ({'message': 'Error Description'}, 500)
        else:
            return ({'message': 'User with id [{}] Not found'.format(user_id)}, 404)


predict

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

Class description:
Class for CNN model

Method signatures and docstrings:
- def __init__(self, num_var, input_dim, output_dim, kernel_size=9, stride=5, hidden_dim=100, num_layers=2, num_epochs=100, learning_rate=0.001): Initilize CNN model Args: num_var: int -- number of covariates as input, one CNN for each covariate input_dim: int -- dimension of the input for fully connected layers after apply cnn output_dim: int -- dimension of the output feature kernel_size: int -- Size of the convolving kernel srtide: int -- Stride of the convolution hidden_dim: int -- number of hidden units for fully connected layers num_layers: int -- number of hidden layers for fully connected layers num_epochs: int -- number of epochs to train learning_rate: float -- learning rate for ADAM
- def forward(self, src, device): Forward function
- def fit(self, train_loader, device): Fit function to CNN
- def fit_cv(self, train_loader, val_src, val_trg, device): Fit function for hyper-parameter tuning
- def predict(self, src, device): Predict function for trained CNN-FNN model to predict

Implement the Python class `CnnFnn` described below.

Class description:
Class for CNN model

Method signatures and docstrings:
- def __init__(self, num_var, input_dim, output_dim, kernel_size=9, stride=5, hidden_dim=100, num_layers=2, num_epochs=100, learning_rate=0.001): Initilize CNN model Args: num_var: int -- number of covariates as input, one CNN for each covariate input_dim: int -- dimension of the input for fully connected layers after apply cnn output_dim: int -- dimension of the output feature kernel_size: int -- Size of the convolving kernel srtide: int -- Stride of the convolution hidden_dim: int -- number of hidden units for fully connected layers num_layers: int -- number of hidden layers for fully connected layers num_epochs: int -- number of epochs to train learning_rate: float -- learning rate for ADAM
- def forward(self, src, device): Forward function
- def fit(self, train_loader, device): Fit function to CNN
- def fit_cv(self, train_loader, val_src, val_trg, device): Fit function for hyper-parameter tuning
- def predict(self, src, device): Predict function for trained CNN-FNN model to predict

<|skeleton|>
class CnnFnn:
    """Class for CNN model"""

    def __init__(self, num_var, input_dim, output_dim, kernel_size=9, stride=5, hidden_dim=100, num_layers=2, num_epochs=100, learning_rate=0.001):
        """Initilize CNN model Args: num_var: int -- number of covariates as input, one CNN for each covariate input_dim: int -- dimension of the input for fully connected layers after apply cnn output_dim: int -- dimension of the output feature kernel_size: int -- Size of the convolving kernel srtide: int -- Stride of the convolution hidden_dim: int -- number of hidden units for fully connected layers num_layers: int -- number of hidden layers for fully connected layers num_epochs: int -- number of epochs to train learning_rate: float -- learning rate for ADAM"""
        <|body_0|>

    def forward(self, src, device):
        """Forward function"""
        <|body_1|>

    def fit(self, train_loader, device):
        """Fit function to CNN"""
        <|body_2|>

    def fit_cv(self, train_loader, val_src, val_trg, device):
        """Fit function for hyper-parameter tuning"""
        <|body_3|>

    def predict(self, src, device):
        """Predict function for trained CNN-FNN model to predict"""
        <|body_4|>

<|end_skeleton|>

<|body_start_0|>
        super(CnnFnn, self).__init__()
        self.num_var = num_var
        self.kernel_size = kernel_size
        self.stride = stride
        self.cnns = nn.ModuleList([nn.Sequential(nn.Conv3d(1, 1, (1, self.kernel_size, self.kernel_size), (1, self.stride, self.stride)), nn.ReLU(inplace=True)) for i in range(self.num_var)])
        self.input_dim = input_dim
        self.output_dim = output_dim
        self.hidden_dim = hidden_dim
        self.num_layers = num_layers
        self.learning_rate = learning_rate
        self.num_epochs = num_epochs
        self.fnn = ReluNet(input_dim=self.input_dim * 4, output_dim=self.output_dim, hidden_dim=self.hidden_dim, num_layers=self.num_layers, num_epochs=self.num_epochs)
<|end_body_0|>

<|body_start_1|>
        for i in range(self.num_var):
            input_x = torch.as_tensor(src[i]).float()
            input_x = input_x.to(device)
            x_out = self.cnns[i](input_x).squeeze(axis=1)
            x_flat = x_out.view(x_out.shape[0], x_out.shape[1], -1)
            if i == 0:
                x_append = x_flat
            else:
                x_append = torch.cat((x_append, x_flat), axis=-1)
        x_append = x_append.view(x_append.shape[0], -1)
        self.fnn = self.fnn.to(device)
        output = self.fnn(x_append)
        return output
<|end_body_1|>

<|body_start_2|>
        optimizer = optim.Adam(self.parameters(), self.learning_rate)
        criterion = torch.nn.MSELoss(reduction='mean')
        max_epoch = self.num_epochs
        for epoch in range(max_epoch):
            self.train()
            train_epoch_loss = 0
            for j, (src, trg) in enumerate(train_loader):
                trg = torch.as_tensor(trg).float().to(device)
                train_output = self.forward(src, device)
                loss = criterion(train_output, trg)
                optimizer.zero_grad()
                loss.backward()
                optimizer.step()
                train_epoch_loss += loss.item()
            print('Epoch: {}/{} Train Loss: {:.4f}'.format(epoch, max_epoch, train_epoch_loss / (j + 1)))
<|end_body_2|>

<|body_start_3|>
        val_trg = torch.as_tensor(val_trg).float().to(device)
        optimizer = optim.Adam(self.parameters(), self.learning_rate)
        criterion = torch.nn.MSELoss(reduction='mean')
        history = np.zeros((self.num_epochs, 2))
        max_epoch = self.num_epochs
        for epoch in range(max_epoch):
            self.train()
            train_epoch_loss = 0
            for j, (src, trg) in enumerate(train_loader):
                trg = torch.as_tensor(trg).float().to(device)
                train_output = self.forward(src, device)
                loss = criterion(train_output, trg)
                optimizer.zero_grad()
                loss.backward()
                optimizer.step()
                train_epoch_loss += loss.item()
            self.eval()
            val_output = self.forward(val_src, device)
            loss = criterion(val_output, val_trg)
            val_epoch_loss = loss.item()
            history[epoch] = [train_epoch_loss / (j + 1), val_epoch_loss]
            print('Epoch: {}/{} Train Loss: {:.4f} Validation Loss:{:.4f}'.format(epoch, self.num_epochs, train_epoch_loss / (j + 1), val_epoch_loss))
        return history
<|end_body_3|>

<|body_start_4|>
        self.eval()
        with torch.no_grad():
            output = self.forward(src, device)
        return output.detach().cpu().numpy()
<|end_body_4|>

Solution:
class CnnFnn:
    """Class for CNN model"""

    def __init__(self, num_var, input_dim, output_dim, kernel_size=9, stride=5, hidden_dim=100, num_layers=2, num_epochs=100, learning_rate=0.001):
        """Initilize CNN model Args: num_var: int -- number of covariates as input, one CNN for each covariate input_dim: int -- dimension of the input for fully connected layers after apply cnn output_dim: int -- dimension of the output feature kernel_size: int -- Size of the convolving kernel srtide: int -- Stride of the convolution hidden_dim: int -- number of hidden units for fully connected layers num_layers: int -- number of hidden layers for fully connected layers num_epochs: int -- number of epochs to train learning_rate: float -- learning rate for ADAM"""
        super(CnnFnn, self).__init__()
        self.num_var = num_var
        self.kernel_size = kernel_size
        self.stride = stride
        self.cnns = nn.ModuleList([nn.Sequential(nn.Conv3d(1, 1, (1, self.kernel_size, self.kernel_size), (1, self.stride, self.stride)), nn.ReLU(inplace=True)) for i in range(self.num_var)])
        self.input_dim = input_dim
        self.output_dim = output_dim
        self.hidden_dim = hidden_dim
        self.num_layers = num_layers
        self.learning_rate = learning_rate
        self.num_epochs = num_epochs
        self.fnn = ReluNet(input_dim=self.input_dim * 4, output_dim=self.output_dim, hidden_dim=self.hidden_dim, num_layers=self.num_layers, num_epochs=self.num_epochs)

    def forward(self, src, device):
        """Forward function"""
        for i in range(self.num_var):
            input_x = torch.as_tensor(src[i]).float()
            input_x = input_x.to(device)
            x_out = self.cnns[i](input_x).squeeze(axis=1)
            x_flat = x_out.view(x_out.shape[0], x_out.shape[1], -1)
            if i == 0:
                x_append = x_flat
            else:
                x_append = torch.cat((x_append, x_flat), axis=-1)
        x_append = x_append.view(x_append.shape[0], -1)
        self.fnn = self.fnn.to(device)
        output = self.fnn(x_append)
        return output

    def fit(self, train_loader, device):
        """Fit function to CNN"""
        optimizer = optim.Adam(self.parameters(), self.learning_rate)
        criterion = torch.nn.MSELoss(reduction='mean')
        max_epoch = self.num_epochs
        for epoch in range(max_epoch):
            self.train()
            train_epoch_loss = 0
            for j, (src, trg) in enumerate(train_loader):
                trg = torch.as_tensor(trg).float().to(device)
                train_output = self.forward(src, device)
                loss = criterion(train_output, trg)
                optimizer.zero_grad()
                loss.backward()
                optimizer.step()
                train_epoch_loss += loss.item()
            print('Epoch: {}/{} Train Loss: {:.4f}'.format(epoch, max_epoch, train_epoch_loss / (j + 1)))

    def fit_cv(self, train_loader, val_src, val_trg, device):
        """Fit function for hyper-parameter tuning"""
        val_trg = torch.as_tensor(val_trg).float().to(device)
        optimizer = optim.Adam(self.parameters(), self.learning_rate)
        criterion = torch.nn.MSELoss(reduction='mean')
        history = np.zeros((self.num_epochs, 2))
        max_epoch = self.num_epochs
        for epoch in range(max_epoch):
            self.train()
            train_epoch_loss = 0
            for j, (src, trg) in enumerate(train_loader):
                trg = torch.as_tensor(trg).float().to(device)
                train_output = self.forward(src, device)
                loss = criterion(train_output, trg)
                optimizer.zero_grad()
                loss.backward()
                optimizer.step()
                train_epoch_loss += loss.item()
            self.eval()
            val_output = self.forward(val_src, device)
            loss = criterion(val_output, val_trg)
            val_epoch_loss = loss.item()
            history[epoch] = [train_epoch_loss / (j + 1), val_epoch_loss]
            print('Epoch: {}/{} Train Loss: {:.4f} Validation Loss:{:.4f}'.format(epoch, self.num_epochs, train_epoch_loss / (j + 1), val_epoch_loss))
        return history

    def predict(self, src, device):
        """Predict function for trained CNN-FNN model to predict"""
        self.eval()
        with torch.no_grad():
            output = self.forward(src, device)
        return output.detach().cpu().numpy()


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

Class description:
An implementation of DARTS: Differentiable Architecture Search.

Method signatures and docstrings:
- def callback_on_start(self): Builds the graphs and assigns parameters to the optimizers.
- def train_on_batch(self, key='train'): Updates the model parameters.
- def valid_on_batch(self): Updates the architecture parameters.

Implement the Python class `DartsSearcher` described below.

Class description:
An implementation of DARTS: Differentiable Architecture Search.

Method signatures and docstrings:
- def callback_on_start(self): Builds the graphs and assigns parameters to the optimizers.
- def train_on_batch(self, key='train'): Updates the model parameters.
- def valid_on_batch(self): Updates the architecture parameters.

<|skeleton|>
class DartsSearcher:
    """An implementation of DARTS: Differentiable Architecture Search."""

    def callback_on_start(self):
        """Builds the graphs and assigns parameters to the optimizers."""
        <|body_0|>

    def train_on_batch(self, key='train'):
        """Updates the model parameters."""
        <|body_1|>

    def valid_on_batch(self):
        """Updates the architecture parameters."""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        self.update_graph('train')
        params_net = self.model.get_net_parameters(grad_only=True)
        self.optimizer['train'].set_parameters(params_net)
        self.update_graph('valid')
        params_arch = self.model.get_arch_parameters(grad_only=True)
        self.optimizer['valid'].set_parameters(params_arch)
        if self.comm.n_procs > 1:
            self._grads_net = [x.grad for x in params_net.values()]
            self._grads_arch = [x.grad for x in params_arch.values()]
            self.event.default_stream_synchronize()
<|end_body_0|>

<|body_start_1|>
        bz, p = (self.mbs_train, self.placeholder['train'])
        self.optimizer[key].zero_grad()
        if self.comm.n_procs > 1:
            self.event.default_stream_synchronize()
        for _ in range(self.accum_train):
            self._load_data(p, self.dataloader['train'].next())
            p['loss'].forward(clear_no_need_grad=True)
            for k, m in p['metrics'].items():
                m.forward(clear_buffer=True)
                self.monitor.update(f'{k}/train', m.d.copy(), bz)
            p['loss'].backward(clear_buffer=True)
            loss = p['loss'].d.copy()
            self.monitor.update('loss/train', loss * self.accum_train, bz)
        if self.comm.n_procs > 1:
            self.comm.all_reduce(self._grads_net, division=True, inplace=False)
            self.event.add_default_stream_event()
        self.optimizer[key].update()
<|end_body_1|>

<|body_start_2|>
        bz, p = (self.mbs_valid, self.placeholder['valid'])
        self.optimizer['valid'].zero_grad()
        if self.comm.n_procs > 1:
            self.event.default_stream_synchronize()
        for _ in range(self.accum_valid):
            self._load_data(p, self.dataloader['valid'].next())
            p['loss'].forward(clear_no_need_grad=True)
            for k, m in p['metrics'].items():
                m.forward(clear_buffer=True)
                self.monitor.update(f'{k}/valid', m.d.copy(), bz)
            p['loss'].backward(clear_buffer=True)
            loss = p['loss'].d.copy()
            self.monitor.update('loss/valid', loss * self.accum_valid, bz)
        if self.comm.n_procs > 1:
            self.comm.all_reduce(self._grads_arch, division=True, inplace=False)
            self.event.add_default_stream_event()
        self.optimizer['valid'].update()
<|end_body_2|>

Solution:
class DartsSearcher:
    """An implementation of DARTS: Differentiable Architecture Search."""

    def callback_on_start(self):
        """Builds the graphs and assigns parameters to the optimizers."""
        self.update_graph('train')
        params_net = self.model.get_net_parameters(grad_only=True)
        self.optimizer['train'].set_parameters(params_net)
        self.update_graph('valid')
        params_arch = self.model.get_arch_parameters(grad_only=True)
        self.optimizer['valid'].set_parameters(params_arch)
        if self.comm.n_procs > 1:
            self._grads_net = [x.grad for x in params_net.values()]
            self._grads_arch = [x.grad for x in params_arch.values()]
            self.event.default_stream_synchronize()

    def train_on_batch(self, key='train'):
        """Updates the model parameters."""
        bz, p = (self.mbs_train, self.placeholder['train'])
        self.optimizer[key].zero_grad()
        if self.comm.n_procs > 1:
            self.event.default_stream_synchronize()
        for _ in range(self.accum_train):
            self._load_data(p, self.dataloader['train'].next())
            p['loss'].forward(clear_no_need_grad=True)
            for k, m in p['metrics'].items():
                m.forward(clear_buffer=True)
                self.monitor.update(f'{k}/train', m.d.copy(), bz)
            p['loss'].backward(clear_buffer=True)
            loss = p['loss'].d.copy()
            self.monitor.update('loss/train', loss * self.accum_train, bz)
        if self.comm.n_procs > 1:
            self.comm.all_reduce(self._grads_net, division=True, inplace=False)
            self.event.add_default_stream_event()
        self.optimizer[key].update()

    def valid_on_batch(self):
        """Updates the architecture parameters."""
        bz, p = (self.mbs_valid, self.placeholder['valid'])
        self.optimizer['valid'].zero_grad()
        if self.comm.n_procs > 1:
            self.event.default_stream_synchronize()
        for _ in range(self.accum_valid):
            self._load_data(p, self.dataloader['valid'].next())
            p['loss'].forward(clear_no_need_grad=True)
            for k, m in p['metrics'].items():
                m.forward(clear_buffer=True)
                self.monitor.update(f'{k}/valid', m.d.copy(), bz)
            p['loss'].backward(clear_buffer=True)
            loss = p['loss'].d.copy()
            self.monitor.update('loss/valid', loss * self.accum_valid, bz)
        if self.comm.n_procs > 1:
            self.comm.all_reduce(self._grads_arch, division=True, inplace=False)
            self.event.add_default_stream_event()
        self.optimizer['valid'].update()


get

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

Class description:
Retrieve a TemplateVersionManager

Method signatures and docstrings:
- def get_object(self, pk, request): Get TemplateVersionManager from db Args: pk: ObjectId request: Returns: TemplateVersionManager
- def get(self, request, pk): Retrieve a TemplateVersionManager Args: request: HTTP request pk: ObjectId Returns: - code: 200 content: TemplateVersionManager - code: 404 content: Object was not found - code: 500 content: Internal server error

Implement the Python class `TemplateVersionManagerDetail` described below.

Class description:
Retrieve a TemplateVersionManager

Method signatures and docstrings:
- def get_object(self, pk, request): Get TemplateVersionManager from db Args: pk: ObjectId request: Returns: TemplateVersionManager
- def get(self, request, pk): Retrieve a TemplateVersionManager Args: request: HTTP request pk: ObjectId Returns: - code: 200 content: TemplateVersionManager - code: 404 content: Object was not found - code: 500 content: Internal server error

<|skeleton|>
class TemplateVersionManagerDetail:
    """Retrieve a TemplateVersionManager"""

    def get_object(self, pk, request):
        """Get TemplateVersionManager from db Args: pk: ObjectId request: Returns: TemplateVersionManager"""
        <|body_0|>

    def get(self, request, pk):
        """Retrieve a TemplateVersionManager Args: request: HTTP request pk: ObjectId Returns: - code: 200 content: TemplateVersionManager - code: 404 content: Object was not found - code: 500 content: Internal server error"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        try:
            return template_version_manager_api.get_by_id(pk, request=request)
        except exceptions.DoesNotExist:
            raise Http404
<|end_body_0|>

<|body_start_1|>
        try:
            template_version_manager_object = self.get_object(pk, request=request)
            serializer = TemplateVersionManagerSerializer(template_version_manager_object)
            return Response(serializer.data)
        except Http404:
            content = {'message': 'Template Version Manager not found.'}
            return Response(content, status=status.HTTP_404_NOT_FOUND)
        except Exception as api_exception:
            content = {'message': str(api_exception)}
            return Response(content, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
<|end_body_1|>

Solution:
class TemplateVersionManagerDetail:
    """Retrieve a TemplateVersionManager"""

    def get_object(self, pk, request):
        """Get TemplateVersionManager from db Args: pk: ObjectId request: Returns: TemplateVersionManager"""
        try:
            return template_version_manager_api.get_by_id(pk, request=request)
        except exceptions.DoesNotExist:
            raise Http404

    def get(self, request, pk):
        """Retrieve a TemplateVersionManager Args: request: HTTP request pk: ObjectId Returns: - code: 200 content: TemplateVersionManager - code: 404 content: Object was not found - code: 500 content: Internal server error"""
        try:
            template_version_manager_object = self.get_object(pk, request=request)
            serializer = TemplateVersionManagerSerializer(template_version_manager_object)
            return Response(serializer.data)
        except Http404:
            content = {'message': 'Template Version Manager not found.'}
            return Response(content, status=status.HTTP_404_NOT_FOUND)
        except Exception as api_exception:
            content = {'message': str(api_exception)}
            return Response(content, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


sumRange

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

Class description:
Implement the NumArray class.

Method signatures and docstrings:
- def __init__(self, nums: List[int]): Precompute, Time: O(n), Space: O(n)
- def sumRange(self, i: int, j: int) -> int: Time: O(1)

Implement the Python class `NumArray` described below.

Class description:
Implement the NumArray class.

Method signatures and docstrings:
- def __init__(self, nums: List[int]): Precompute, Time: O(n), Space: O(n)
- def sumRange(self, i: int, j: int) -> int: Time: O(1)

<|skeleton|>
class NumArray:

    def __init__(self, nums: List[int]):
        """Precompute, Time: O(n), Space: O(n)"""
        <|body_0|>

    def sumRange(self, i: int, j: int) -> int:
        """Time: O(1)"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        n = len(nums)
        if n == 0:
            return
        dp = [0] * n
        dp[0] = nums[0]
        for i in range(1, n):
            dp[i] = dp[i - 1] + nums[i]
        self.dp = dp
<|end_body_0|>

<|body_start_1|>
        """(i, j) = (0, j) - (0, i-1)"""
        if self.dp is None:
            return 0
        if i == 0:
            return self.dp[j]
        return self.dp[j] - self.dp[i - 1]
<|end_body_1|>

Solution:
class NumArray:
    def __init__(self, nums: List[int]):
        """Precompute, Time: O(n), Space: O(n)"""
        n = len(nums)
        if n == 0:
            return
        dp = [0] * n
        dp[0] = nums[0]
        for i in range(1, n):
            dp[i] = dp[i - 1] + nums[i]
        self.dp = dp

    def sumRange(self, i: int, j: int) -> int:
        """Time: O(1)"""
        """(i, j) = (0, j) - (0, i-1)"""
        if self.dp is None:
            return 0
        if i == 0:
            return self.dp[j]
        return self.dp[j] - self.dp[i - 1]

python/303-Range Sum Query - Immutable.py


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

Class description:
base class for loading items from responses

Method signatures and docstrings:
- def add_dependent(self, name, the_item): adds a dependent item to the item loader
- def load_item(self, *args, **kwargs): subclasses load_item to handle dependents

Implement the Python class `BaseLoader` described below.

Class description:
base class for loading items from responses

Method signatures and docstrings:
- def add_dependent(self, name, the_item): adds a dependent item to the item loader
- def load_item(self, *args, **kwargs): subclasses load_item to handle dependents

<|skeleton|>
class BaseLoader:
    """base class for loading items from responses"""

    def add_dependent(self, name, the_item):
        """adds a dependent item to the item loader"""
        <|body_0|>

    def load_item(self, *args, **kwargs):
        """subclasses load_item to handle dependents"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self._dependents.append(name)
        if the_item is not None:
            self.add_value(name, the_item)
<|end_body_0|>

<|body_start_1|>
        the_item = super().load_item(*args, **kwargs)
        the_item._dependents = self._dependents
        return the_item
<|end_body_1|>

Solution:
class BaseLoader:
    """base class for loading items from responses"""

    def add_dependent(self, name, the_item):
        """adds a dependent item to the item loader"""
        self._dependents.append(name)
        if the_item is not None:
            self.add_value(name, the_item)

    def load_item(self, *args, **kwargs):
        """subclasses load_item to handle dependents"""
        the_item = super().load_item(*args, **kwargs)
        the_item._dependents = self._dependents
        return the_item


execute

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

Class description:
Defines an analysis task list. This class defines an task list that is executed in parallel on an executor.

Method signatures and docstrings:
- def __init__(self, executor, cfg): Configures the analysis tasklist from a dictionary. For each key-value pair in "cfg_analysis", an analysis task is instantiated and appended to a list. On a call to execute, all tasks are launched with the current data. Args: executor (PEP-3148 style executor): Executor on which all analysis tasks are launched cfg: Delta configuration Returns: None
- def execute(self, timechunk): Execute all analysis tasks. Args: timechunk (timechunk): A time-chunk of 2D image data. Returns: None

Implement the Python class `tasklist` described below.

Class description:
Defines an analysis task list. This class defines an task list that is executed in parallel on an executor.

Method signatures and docstrings:
- def __init__(self, executor, cfg): Configures the analysis tasklist from a dictionary. For each key-value pair in "cfg_analysis", an analysis task is instantiated and appended to a list. On a call to execute, all tasks are launched with the current data. Args: executor (PEP-3148 style executor): Executor on which all analysis tasks are launched cfg: Delta configuration Returns: None
- def execute(self, timechunk): Execute all analysis tasks. Args: timechunk (timechunk): A time-chunk of 2D image data. Returns: None

<|skeleton|>
class tasklist:
    """Defines an analysis task list. This class defines an task list that is executed in parallel on an executor."""

    def __init__(self, executor, cfg):
        """Configures the analysis tasklist from a dictionary. For each key-value pair in "cfg_analysis", an analysis task is instantiated and appended to a list. On a call to execute, all tasks are launched with the current data. Args: executor (PEP-3148 style executor): Executor on which all analysis tasks are launched cfg: Delta configuration Returns: None"""
        <|body_0|>

    def execute(self, timechunk):
        """Execute all analysis tasks. Args: timechunk (timechunk): A time-chunk of 2D image data. Returns: None"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.logger = logging.getLogger('simple')
        self.cfg = cfg
        self.executor = executor
        self.tasklist = []
        for key, anl_params in cfg['analysis'].items():
            try:
                self.tasklist.append(get_analysis_task(key, anl_params, cfg['storage']))
            except NameError as e:
                self.logger.error(f'Could not find a suitable analysis task: {e}')
                continue
            self.logger.info(f'Added {key} to analysis task list')
<|end_body_0|>

<|body_start_1|>
        self.logger.info(f'Submitting timechunk {timechunk.tb.chunk_idx} to analysis tasklist')
        for task in self.tasklist:
            task.execute(timechunk, self.executor)
<|end_body_1|>

Solution:
class tasklist:
    """Defines an analysis task list. This class defines an task list that is executed in parallel on an executor."""

    def __init__(self, executor, cfg):
        """Configures the analysis tasklist from a dictionary. For each key-value pair in "cfg_analysis", an analysis task is instantiated and appended to a list. On a call to execute, all tasks are launched with the current data. Args: executor (PEP-3148 style executor): Executor on which all analysis tasks are launched cfg: Delta configuration Returns: None"""
        self.logger = logging.getLogger('simple')
        self.cfg = cfg
        self.executor = executor
        self.tasklist = []
        for key, anl_params in cfg['analysis'].items():
            try:
                self.tasklist.append(get_analysis_task(key, anl_params, cfg['storage']))
            except NameError as e:
                self.logger.error(f'Could not find a suitable analysis task: {e}')
                continue
            self.logger.info(f'Added {key} to analysis task list')

    def execute(self, timechunk):
        """Execute all analysis tasks. Args: timechunk (timechunk): A time-chunk of 2D image data. Returns: None"""
        self.logger.info(f'Submitting timechunk {timechunk.tb.chunk_idx} to analysis tasklist')
        for task in self.tasklist:
            task.execute(timechunk, self.executor)


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

Class description:
`CalcJob` implementation for the cp.x code of Quantum ESPRESSO.

Method signatures and docstrings:
- def xml_filepaths(cls): Return a list of relative filepaths of XML files.
- def define(cls, spec): Define the process specification.
- def _generate_PWCP_input_tail(*args, **kwargs): Parse CP specific input parameters.

Implement the Python class `CpCalculation` described below.

Class description:
`CalcJob` implementation for the cp.x code of Quantum ESPRESSO.

Method signatures and docstrings:
- def xml_filepaths(cls): Return a list of relative filepaths of XML files.
- def define(cls, spec): Define the process specification.
- def _generate_PWCP_input_tail(*args, **kwargs): Parse CP specific input parameters.

<|skeleton|>
class CpCalculation:
    """`CalcJob` implementation for the cp.x code of Quantum ESPRESSO."""

    def xml_filepaths(cls):
        """Return a list of relative filepaths of XML files."""
        <|body_0|>

    def define(cls, spec):
        """Define the process specification."""
        <|body_1|>

    def _generate_PWCP_input_tail(*args, **kwargs):
        """Parse CP specific input parameters."""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        filepaths = []
        for filename in cls.xml_filenames:
            filepath = os.path.join(cls._OUTPUT_SUBFOLDER, f'{cls._PREFIX}_{cls._CP_WRITE_UNIT_NUMBER}.save', filename)
            filepaths.append(filepath)
        return filepaths
<|end_body_0|>

<|body_start_1|>
        super().define(spec)
        spec.input('metadata.options.parser_name', valid_type=str, default='quantumespresso.cp')
        spec.output('output_trajectory', valid_type=orm.TrajectoryData)
        spec.output('output_parameters', valid_type=orm.Dict)
        spec.default_output_node = 'output_parameters'
        spec.exit_code(301, 'ERROR_NO_RETRIEVED_TEMPORARY_FOLDER', message='The retrieved temporary folder could not be accessed.')
        spec.exit_code(303, 'ERROR_MISSING_XML_FILE', message='The required XML file is not present in the retrieved folder.')
        spec.exit_code(304, 'ERROR_OUTPUT_XML_MULTIPLE', message='The retrieved folder contains multiple XML files.')
        spec.exit_code(320, 'ERROR_OUTPUT_XML_READ', message='The required XML file could not be read.')
        spec.exit_code(330, 'ERROR_READING_POS_FILE', message='The required POS file could not be read.')
        spec.exit_code(340, 'ERROR_READING_TRAJECTORY_DATA', message='The required trajectory data could not be read.')
<|end_body_1|>

<|body_start_2|>
        settings = kwargs['settings']
        autopilot = settings.pop('AUTOPILOT', [])
        if not autopilot:
            return ''
        autopilot_card = 'AUTOPILOT\n'
        try:
            for event in autopilot:
                if isinstance(event['newvalue'], str):
                    autopilot_card += f"ON_STEP = {event['onstep']} : '{event['what']}' = {event['newvalue']}\n"
                else:
                    autopilot_card += f"ON_STEP = {event['onstep']} : {event['what']} = {event['newvalue']}\n"
        except KeyError as exception:
            raise exceptions.InputValidationError(f"AUTOPILOT input: you must specify a list of dictionaries like the following:\n                 [\n                    {{'onstep' : 10, 'what' : 'dt', 'newvalue' : 5.0 }},\n                    {{'onstep' : 20, 'what' : 'whatever', 'newvalue' : 'pippo'}}\n                 ]\n                 You specified {autopilot}\n                 ") from exception
        autopilot_card += 'ENDRULES\n'
        return autopilot_card
<|end_body_2|>

Solution:
class CpCalculation:
    """`CalcJob` implementation for the cp.x code of Quantum ESPRESSO."""

    def xml_filepaths(cls):
        """Return a list of relative filepaths of XML files."""
        filepaths = []
        for filename in cls.xml_filenames:
            filepath = os.path.join(cls._OUTPUT_SUBFOLDER, f'{cls._PREFIX}_{cls._CP_WRITE_UNIT_NUMBER}.save', filename)
            filepaths.append(filepath)
        return filepaths

    def define(cls, spec):
        """Define the process specification."""
        super().define(spec)
        spec.input('metadata.options.parser_name', valid_type=str, default='quantumespresso.cp')
        spec.output('output_trajectory', valid_type=orm.TrajectoryData)
        spec.output('output_parameters', valid_type=orm.Dict)
        spec.default_output_node = 'output_parameters'
        spec.exit_code(301, 'ERROR_NO_RETRIEVED_TEMPORARY_FOLDER', message='The retrieved temporary folder could not be accessed.')
        spec.exit_code(303, 'ERROR_MISSING_XML_FILE', message='The required XML file is not present in the retrieved folder.')
        spec.exit_code(304, 'ERROR_OUTPUT_XML_MULTIPLE', message='The retrieved folder contains multiple XML files.')
        spec.exit_code(320, 'ERROR_OUTPUT_XML_READ', message='The required XML file could not be read.')
        spec.exit_code(330, 'ERROR_READING_POS_FILE', message='The required POS file could not be read.')
        spec.exit_code(340, 'ERROR_READING_TRAJECTORY_DATA', message='The required trajectory data could not be read.')

    def _generate_PWCP_input_tail(*args, **kwargs):
        """Parse CP specific input parameters."""
        settings = kwargs['settings']
        autopilot = settings.pop('AUTOPILOT', [])
        if not autopilot:
            return ''
        autopilot_card = 'AUTOPILOT\n'
        try:
            for event in autopilot:
                if isinstance(event['newvalue'], str):
                    autopilot_card += f"ON_STEP = {event['onstep']} : '{event['what']}' = {event['newvalue']}\n"
                else:
                    autopilot_card += f"ON_STEP = {event['onstep']} : {event['what']} = {event['newvalue']}\n"
        except KeyError as exception:
            raise exceptions.InputValidationError(f"AUTOPILOT input: you must specify a list of dictionaries like the following:\n                 [\n                    {{'onstep' : 10, 'what' : 'dt', 'newvalue' : 5.0 }},\n                    {{'onstep' : 20, 'what' : 'whatever', 'newvalue' : 'pippo'}}\n                 ]\n                 You specified {autopilot}\n                 ") from exception
        autopilot_card += 'ENDRULES\n'
        return autopilot_card


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

Class description:
Implement the TestMaximalSquare class.

Method signatures and docstrings:
- def test_returns_zero_if_no_ones(self): Takes in a matrix of 0s and returns 0
- def test_returns_one_for_one_cell(self): Takes in a matrix with only one 1 and returns 1
- def test_can_dynamically_calculate_larger_square_areas(self): Takes in a large matrix with a large square area and returns result

Implement the Python class `TestMaximalSquare` described below.

Class description:
Implement the TestMaximalSquare class.

Method signatures and docstrings:
- def test_returns_zero_if_no_ones(self): Takes in a matrix of 0s and returns 0
- def test_returns_one_for_one_cell(self): Takes in a matrix with only one 1 and returns 1
- def test_can_dynamically_calculate_larger_square_areas(self): Takes in a large matrix with a large square area and returns result

<|skeleton|>
class TestMaximalSquare:

    def test_returns_zero_if_no_ones(self):
        """Takes in a matrix of 0s and returns 0"""
        <|body_0|>

    def test_returns_one_for_one_cell(self):
        """Takes in a matrix with only one 1 and returns 1"""
        <|body_1|>

    def test_can_dynamically_calculate_larger_square_areas(self):
        """Takes in a large matrix with a large square area and returns result"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        matrix = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
        result = maximal_square(matrix)
        self.assertEqual(result, 0)
<|end_body_0|>

<|body_start_1|>
        matrix = [[0, 0, 1], [0, 0, 0], [0, 0, 0]]
        result = maximal_square(matrix)
        self.assertEqual(result, 1)
<|end_body_1|>

<|body_start_2|>
        matrix = [[1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 0, 1], [1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 0], [1, 1, 1, 0, 0, 0]]
        result = maximal_square(matrix)
        self.assertEqual(result, 9)
<|end_body_2|>

Solution:
class TestMaximalSquare:
    def test_returns_zero_if_no_ones(self):
        """Takes in a matrix of 0s and returns 0"""
        matrix = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
        result = maximal_square(matrix)
        self.assertEqual(result, 0)

    def test_returns_one_for_one_cell(self):
        """Takes in a matrix with only one 1 and returns 1"""
        matrix = [[0, 0, 1], [0, 0, 0], [0, 0, 0]]
        result = maximal_square(matrix)
        self.assertEqual(result, 1)

    def test_can_dynamically_calculate_larger_square_areas(self):
        """Takes in a large matrix with a large square area and returns result"""
        matrix = [[1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 0, 1], [1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 0], [1, 1, 1, 0, 0, 0]]
        result = maximal_square(matrix)
        self.assertEqual(result, 9)


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

Class description:
Metaclass used for building CRS Enum class

Method signatures and docstrings:
- def __new__(mcs, cls, bases, classdict): This is executed at the beginning of runtime when CRS class is created
- def __call__(cls, crs_value, *args, **kwargs): This is executed whenever CRS('something') is called
- def _parse_crs(value: object) -> object: Method for parsing different inputs representing the same CRS enum. Examples: - 4326 - 'EPSG:3857' - {'init': 32633} - geojson['crs']['properties']['name'] string (urn:ogc:def:crs:...) - pyproj.CRS(32743)

Implement the Python class `CRSMeta` described below.

Class description:
Metaclass used for building CRS Enum class

Method signatures and docstrings:
- def __new__(mcs, cls, bases, classdict): This is executed at the beginning of runtime when CRS class is created
- def __call__(cls, crs_value, *args, **kwargs): This is executed whenever CRS('something') is called
- def _parse_crs(value: object) -> object: Method for parsing different inputs representing the same CRS enum. Examples: - 4326 - 'EPSG:3857' - {'init': 32633} - geojson['crs']['properties']['name'] string (urn:ogc:def:crs:...) - pyproj.CRS(32743)

<|skeleton|>
class CRSMeta:
    """Metaclass used for building CRS Enum class"""

    def __new__(mcs, cls, bases, classdict):
        """This is executed at the beginning of runtime when CRS class is created"""
        <|body_0|>

    def __call__(cls, crs_value, *args, **kwargs):
        """This is executed whenever CRS('something') is called"""
        <|body_1|>

    def _parse_crs(value: object) -> object:
        """Method for parsing different inputs representing the same CRS enum. Examples: - 4326 - 'EPSG:3857' - {'init': 32633} - geojson['crs']['properties']['name'] string (urn:ogc:def:crs:...) - pyproj.CRS(32743)"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        for direction, direction_value in [('N', '6'), ('S', '7')]:
            for zone in range(1, 61):
                classdict[f'UTM_{zone}{direction}'] = f'32{direction_value}{zone:02}'
        return super().__new__(mcs, cls, bases, classdict)
<|end_body_0|>

<|body_start_1|>
        crs_value = cls._parse_crs(crs_value)
        if isinstance(crs_value, str) and (not cls.has_value(crs_value)) and crs_value.isdigit() and (len(crs_value) >= 4):
            crs_name = f'EPSG_{crs_value}'
            extend_enum(cls, crs_name, crs_value)
        return super().__call__(crs_value, *args, **kwargs)
<|end_body_1|>

<|body_start_2|>
        if isinstance(value, dict) and 'init' in value:
            value = value['init']
        if hasattr(value, 'to_epsg'):
            if value == CRSMeta._UNSUPPORTED_CRS:
                message = 'sentinelhub-py supports only WGS 84 coordinate reference system with coordinate order lng-lat. Given pyproj.CRS(4326) has coordinate order lat-lng. Be careful to use the correct order of coordinates.'
                warnings.warn(message, category=SHUserWarning)
            epsg_code = value.to_epsg()
            if epsg_code is not None:
                return str(epsg_code)
            if value == CRS.WGS84.pyproj_crs():
                return '4326'
            error_message = f'Failed to determine an EPSG code of the given CRS:\n{repr(value)}'
            maybe_epsg = value.to_epsg(min_confidence=0)
            if maybe_epsg is not None:
                error_message = f'{error_message}\nIt might be EPSG {maybe_epsg} but pyproj is not confident enough.'
            raise ValueError(error_message)
        if isinstance(value, (int, np.integer)):
            return str(value)
        if isinstance(value, str):
            if 'urn:ogc:def:crs' in value.lower():
                crs_template = re.compile('urn:ogc:def:crs:.+::(?P<code>.+)', re.IGNORECASE)
                match = crs_template.match(value)
                if match is None:
                    raise ValueError(f'The value {value} could not be parsed to a CRS.')
                value = match.group('code')
            if value.upper() == 'CRS84':
                return '4326'
            return value.lower().replace('epsg:', '').strip()
        return value
<|end_body_2|>

Solution:
class CRSMeta:
    """Metaclass used for building CRS Enum class"""

    def __new__(mcs, cls, bases, classdict):
        """This is executed at the beginning of runtime when CRS class is created"""
        for direction, direction_value in [('N', '6'), ('S', '7')]:
            for zone in range(1, 61):
                classdict[f'UTM_{zone}{direction}'] = f'32{direction_value}{zone:02}'
        return super().__new__(mcs, cls, bases, classdict)

    def __call__(cls, crs_value, *args, **kwargs):
        """This is executed whenever CRS('something') is called"""
        crs_value = cls._parse_crs(crs_value)
        if isinstance(crs_value, str) and (not cls.has_value(crs_value)) and crs_value.isdigit() and (len(crs_value) >= 4):
            crs_name = f'EPSG_{crs_value}'
            extend_enum(cls, crs_name, crs_value)
        return super().__call__(crs_value, *args, **kwargs)

    def _parse_crs(value: object) -> object:
        """Method for parsing different inputs representing the same CRS enum. Examples: - 4326 - 'EPSG:3857' - {'init': 32633} - geojson['crs']['properties']['name'] string (urn:ogc:def:crs:...) - pyproj.CRS(32743)"""
        if isinstance(value, dict) and 'init' in value:
            value = value['init']
        if hasattr(value, 'to_epsg'):
            if value == CRSMeta._UNSUPPORTED_CRS:
                message = 'sentinelhub-py supports only WGS 84 coordinate reference system with coordinate order lng-lat. Given pyproj.CRS(4326) has coordinate order lat-lng. Be careful to use the correct order of coordinates.'
                warnings.warn(message, category=SHUserWarning)
            epsg_code = value.to_epsg()
            if epsg_code is not None:
                return str(epsg_code)
            if value == CRS.WGS84.pyproj_crs():
                return '4326'
            error_message = f'Failed to determine an EPSG code of the given CRS:\n{repr(value)}'
            maybe_epsg = value.to_epsg(min_confidence=0)
            if maybe_epsg is not None:
                error_message = f'{error_message}\nIt might be EPSG {maybe_epsg} but pyproj is not confident enough.'
            raise ValueError(error_message)
        if isinstance(value, (int, np.integer)):
            return str(value)
        if isinstance(value, str):
            if 'urn:ogc:def:crs' in value.lower():
                crs_template = re.compile('urn:ogc:def:crs:.+::(?P<code>.+)', re.IGNORECASE)
                match = crs_template.match(value)
                if match is None:
                    raise ValueError(f'The value {value} could not be parsed to a CRS.')
                value = match.group('code')
            if value.upper() == 'CRS84':
                return '4326'
            return value.lower().replace('epsg:', '').strip()
        return value


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

Class description:
Class with unittests for SameBSTs.py

Method signatures and docstrings:
- def setUp(self): Sets up input.
- def test_user_input(self): Checks if method works properly. Input cannot be empty string.

Implement the Python class `test_SameBSTs` described below.

Class description:
Class with unittests for SameBSTs.py

Method signatures and docstrings:
- def setUp(self): Sets up input.
- def test_user_input(self): Checks if method works properly. Input cannot be empty string.

<|skeleton|>
class test_SameBSTs:
    """Class with unittests for SameBSTs.py"""

    def setUp(self):
        """Sets up input."""
        <|body_0|>

    def test_user_input(self):
        """Checks if method works properly. Input cannot be empty string."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.arrayOne = [10, 15, 8, 12, 94, 81, 5, 2, 11]
        self.arrayTwo = [10, 8, 5, 15, 2, 12, 11, 94, 81]
        self.output = True
        return (self.arrayOne, self.arrayTwo, self.output)
<|end_body_0|>

<|body_start_1|>
        arrayOne, arrayTwo, output = self.setUp()
        output_method = sameBSTs(arrayOne, arrayTwo)
        self.assertEqual(output, output_method)
<|end_body_1|>

Solution:
class test_SameBSTs:
    """Class with unittests for SameBSTs.py"""

    def setUp(self):
        """Sets up input."""
        self.arrayOne = [10, 15, 8, 12, 94, 81, 5, 2, 11]
        self.arrayTwo = [10, 8, 5, 15, 2, 12, 11, 94, 81]
        self.output = True
        return (self.arrayOne, self.arrayTwo, self.output)

    def test_user_input(self):
        """Checks if method works properly. Input cannot be empty string."""
        arrayOne, arrayTwo, output = self.setUp()
        output_method = sameBSTs(arrayOne, arrayTwo)
        self.assertEqual(output, output_method)


exchange

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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def exchange(self, nums: List[int]) -> List[int]: 双指针, 动态规划 使i为奇偶边缘的第一个偶数下标 j向右走 :param nums: :return:
- def exchange(self, nums: List[int]) -> List[int]: 双指针 i开头 j末尾 :param nums: :return:

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def exchange(self, nums: List[int]) -> List[int]: 双指针, 动态规划 使i为奇偶边缘的第一个偶数下标 j向右走 :param nums: :return:
- def exchange(self, nums: List[int]) -> List[int]: 双指针 i开头 j末尾 :param nums: :return:

<|skeleton|>
class Solution:

    def exchange(self, nums: List[int]) -> List[int]:
        """双指针, 动态规划 使i为奇偶边缘的第一个偶数下标 j向右走 :param nums: :return:"""
        <|body_0|>

    def exchange(self, nums: List[int]) -> List[int]:
        """双指针 i开头 j末尾 :param nums: :return:"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        if len(nums) == 0:
            return []
        i, j = (0, 0)
        while j < len(nums):
            if nums[j] % 2 != 0:
                nums[i], nums[j] = (nums[j], nums[i])
                i += 1
            j += 1
        return nums
<|end_body_0|>

<|body_start_1|>
        if len(nums) == 0:
            return []
        i, j = (0, len(nums) - 1)
        while i < j:
            while i < j and nums[i] % 2 != 0:
                i += 1
            while i < j and nums[j] % 2 == 0:
                j -= 1
            nums[i], nums[j] = (nums[j], nums[i])
        return nums
<|end_body_1|>

Solution:
class Solution:
    def exchange(self, nums: List[int]) -> List[int]:
        """双指针, 动态规划 使i为奇偶边缘的第一个偶数下标 j向右走 :param nums: :return:"""
        if len(nums) == 0:
            return []
        i, j = (0, 0)
        while j < len(nums):
            if nums[j] % 2 != 0:
                nums[i], nums[j] = (nums[j], nums[i])
                i += 1
            j += 1
        return nums

    def exchange(self, nums: List[int]) -> List[int]:
        """双指针 i开头 j末尾 :param nums: :return:"""
        if len(nums) == 0:
            return []
        i, j = (0, len(nums) - 1)
        while i < j:
            while i < j and nums[i] % 2 != 0:
                i += 1
            while i < j and nums[j] % 2 == 0:
                j -= 1
            nums[i], nums[j] = (nums[j], nums[i])
        return nums


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

Class description:
Implement the UpdateHost class.

Method signatures and docstrings:
- def parameter_check(self, data): 校验参数 :param data: :return:
- def post(self, request): 修改host域名 :param request: :return:

Implement the Python class `UpdateHost` described below.

Class description:
Implement the UpdateHost class.

Method signatures and docstrings:
- def parameter_check(self, data): 校验参数 :param data: :return:
- def post(self, request): 修改host域名 :param request: :return:

<|skeleton|>
class UpdateHost:

    def parameter_check(self, data):
        """校验参数 :param data: :return:"""
        <|body_0|>

    def post(self, request):
        """修改host域名 :param request: :return:"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        try:
            if not isinstance(data['project_id'], int) or not isinstance(data['id'], int):
                return JsonResponse(code='999995', msg='参数有误！')
            if not data['name'] or not data['host']:
                return JsonResponse(code='999995', msg='参数有误！')
        except KeyError:
            return JsonResponse(code='999995', msg='参数有误！')
<|end_body_0|>

<|body_start_1|>
        data = JSONParser().parse(request)
        result = self.parameter_check(data)
        if result:
            return result
        try:
            pro_data = Project.objects.get(id=data['project_id'])
            if not request.user.is_superuser and pro_data.user.is_superuser:
                return JsonResponse(code='999983', msg='无操作权限！')
        except ObjectDoesNotExist:
            return JsonResponse(code='999995', msg='项目不存在！')
        pro_data = ProjectSerializer(pro_data)
        if not pro_data.data['status']:
            return JsonResponse(code='999985', msg='该项目已禁用')
        try:
            obi = GlobalHost.objects.get(id=data['id'])
        except ObjectDoesNotExist:
            return JsonResponse(code='999992', msg='host不存在！')
        host_name = GlobalHost.objects.filter(name=data['name']).exclude(id=data['id'])
        if len(host_name):
            return JsonResponse(code='999997', msg='存在相同名称！')
        else:
            serializer = GlobalHostSerializer(data=data)
            with transaction.atomic():
                if serializer.is_valid():
                    serializer.update(instance=obi, validated_data=data)
                    record_dynamic(project=data['project_id'], _type='修改', operationObject='域名', user=request.user.pk, data=data['name'])
                    return JsonResponse(code='999999', msg='成功！')
                return JsonResponse(code='999998', msg='失败！')
<|end_body_1|>

Solution:
class UpdateHost:
    def parameter_check(self, data):
        """校验参数 :param data: :return:"""
        try:
            if not isinstance(data['project_id'], int) or not isinstance(data['id'], int):
                return JsonResponse(code='999995', msg='参数有误！')
            if not data['name'] or not data['host']:
                return JsonResponse(code='999995', msg='参数有误！')
        except KeyError:
            return JsonResponse(code='999995', msg='参数有误！')

    def post(self, request):
        """修改host域名 :param request: :return:"""
        data = JSONParser().parse(request)
        result = self.parameter_check(data)
        if result:
            return result
        try:
            pro_data = Project.objects.get(id=data['project_id'])
            if not request.user.is_superuser and pro_data.user.is_superuser:
                return JsonResponse(code='999983', msg='无操作权限！')
        except ObjectDoesNotExist:
            return JsonResponse(code='999995', msg='项目不存在！')
        pro_data = ProjectSerializer(pro_data)
        if not pro_data.data['status']:
            return JsonResponse(code='999985', msg='该项目已禁用')
        try:
            obi = GlobalHost.objects.get(id=data['id'])
        except ObjectDoesNotExist:
            return JsonResponse(code='999992', msg='host不存在！')
        host_name = GlobalHost.objects.filter(name=data['name']).exclude(id=data['id'])
        if len(host_name):
            return JsonResponse(code='999997', msg='存在相同名称！')
        else:
            serializer = GlobalHostSerializer(data=data)
            with transaction.atomic():
                if serializer.is_valid():
                    serializer.update(instance=obi, validated_data=data)
                    record_dynamic(project=data['project_id'], _type='修改', operationObject='域名', user=request.user.pk, data=data['name'])
                    return JsonResponse(code='999999', msg='成功！')
                return JsonResponse(code='999998', msg='失败！')